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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With