1

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: "[email protected]",
    address:{},
    name: "name"
}

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

...
user: {
   name: "name"
}
1
  • 1
    You can use unset in aggregation pipeline. check this for populate Commented Jun 2, 2022 at 19:10

2 Answers 2

3

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'  });
Sign up to request clarification or add additional context in comments.

Comments

2

As i understand mongoose documentation https://mongoosejs.com/docs/populate.html, populate as $lookup is use to resolve a relation with other collection.

MongoDB has the join-like $lookup aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called populate(), which lets you reference documents in other collections.

In your case, you don't need to resolve a field with an other collection. You already have the final data you target . You could use $project at the end of your pipeline aggregation to keep only name field, like :

{ $project: { name:1 } }

Let me know if i helped you.

Edit :

I read too fast, if you have this data res after the populate and not after the aggreg, you may select your final field, like is said here https://stackoverflow.com/a/72481338/16205278

user: {
    email: "[email protected]",
    address:{},
    name: "name"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.