Mongoose find() Certain Fields
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.
// will return all documents with just the document's age, name, and _id properties
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!
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!