Search code examples
javascriptmongodbexpressmongooseaggregate

Exclude certain attributes from object using the populate from mongodb using aggregate


I want to exclude for example email and address using populate() function from mongodb, just get the name from it:

Example:

const results = await Seller.aggregate(aggregatePipeline).exec();
const sellers = await Seller.populate(results, { path: "user" });

When populating the user instead of having:

...
user: {
    email: "hgjh@gmail.com",
    address:{},
    name: "name"
}

I want to only have (exclude certain data from the path):

...
user: {
   name: "name"
}

Solution

  • You can do either,

    const sellers = await Seller.populate(results, { path: "user", select: '- 
    email -address'  });
    

    or

    const sellers = await Seller.populate(results, { path: "user", select: 
    'name'  });