Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose/Mongodb: Exclude fields from populated query data

I use the following mongoose query in a MEAN-environment to find and output a particular author and his corresponding books.

Author .findOne({personcode: code}) .select('-_id') .select('-__v') .populate('bookids') //referencing to book documents in another collection (->array of bookids) .select('-_id') //this doens't affect the data coming from the bookids-documents .select('-__v') //this doens't affect the data coming from the bookids-documents .exec(function (err, data) {    //foo }); 

I would also like to exclude the "_id" and "__v" fields from the populated data coming from the external documents. How can that be achieved?

like image 977
Igor P. Avatar asked Nov 13 '14 17:11

Igor P.


People also ask

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

How population works in mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

Can I use $in in mongoose?

For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.


1 Answers

The second parameter of populate is a field selection string, so you can do this as:

Author   .findOne({personcode: code})   .select('-_id -__v')   .populate('bookids', '-_id -__v')   .exec(function (err, data) {     //foo }); 

Note that you should combine your field selections into a single string.

like image 135
JohnnyHK Avatar answered Sep 19 '22 18:09

JohnnyHK