Mongoose find() Certain Fields – Mastering JS

0
80
How to Filter an Object by Key in JavaScript


Apr 27, 2022

To filter object properties in mongoose, you can use the select() function on the query.
The select() function allows you to select the fields you wish to return.


await Model.find({}).select('name age');

The _id property

MongoDB includes _id by default.
To exclude the _id when picking fields, you need to do .find().select({ name: 1, _id: 0 }) or .find().select('name -_id').
The 0 and - tells Mongoose and the MongoDB server to explicitly exclude _id.

await Model.find().select({ name: 1, _id: 0 });

Or

await Model.find().select({'name -_id'});


Want to become your team’s MongoDB expert? “Mastering Mongoose” distills 8 years of hard-earned
lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need
to know to build production-ready full-stack apps with Node.js and MongoDB in a few days.
Get your copy!


More Mongoose Tutorials



Source link

Leave a reply

Please enter your comment!
Please enter your name here