Regarding the mongoose populate

[
    {
        "gstin": "07AAACH0812J1ZY",
        "company_name": "HERO MOTOCORP LIMITED",
        "status": "Approved",
        "createdBy": {
            "name": "BagalVarsha",
            "email": "varsha.p.patil@tech-trail.com",
            "mobile_number": 9421492671
        }
    },

after populating data i don’t want data like this i want data in main schema is there in a way to do it
example:

[
    {
        "gstin": "07AAACH0812J1ZY",
        "company_name": "HERO MOTOCORP LIMITED",
        "status": "Approved",
            "name": "BagalVarsha",
            "email": "varsha.p.patil@tech-trail.com",
            "mobile_number": 9421492671
        
    },

Hi @Kashif_Iqbal,
Mongoose’s .populate() method does not provide the ability to flatten the document. There’s a feature request in the mongoose’s official GitHub repository to do that.

Off the top of my head, there are 2 different ways using which you can achieve this transformation:

  1. Client Side Transformation: You can fetch documents using .populate() in the same way as you are currently fetching and then you can transform(flatten) the documents on your server.
const ordersArray = Order.find().populate("user");
const transformedOrdersArray = ordersArray.map((order) => ({
  gstin: order.gstin,
  company_name: order.company_name,
  status: order.status,
  // Transferring the following values from the 
  // embedded user object to the parent object
  name: order.user.name, 
  email: order.user.email,
  mobile_number: order.user.mobile_number,
}));
  1. Use Aggregation Pipeline: You can utilise the aggregation pipeline provided by MongoDB to process and transform multiple documents efficiently, hence you won’t need to transform the array returned by MongoDB and you can use the returned results as it is.
const orders = Order.aggregate(
  [
    { $match: { _id: ObjectId(orderId) } },
    { $lookup: { from: "users", localField: "createdBy", foreignField: "_id", as: "createdBy" } },
    { $unwind: "$createdBy" },
    {
      $project: {
        gstin: "$gstin",
        company_name: "$company_name",
        status: "$status",
        // Transferring the following values from the 
        // embedded user(createdBy) object to the parent object
        name: "$order.createdBy.name", 
        email: "$order.createdBy.email",
        mobile_number: "$order.createdBy.mobile_number",
    }}
  ]
)

If you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
MongoDB

3 Likes