Mongoose, find, return specific properties
Mongoose provides multiple ways to project documents with find
, findOne
, and findById
.
1. Projection as String:
// INCLUDE SPECIFIC FIELDS
// find user and return only name and phone fields
User.findOne({ email: email }, 'name phone');
// EXCLUDE SPECIFIC FIELD
// find user and return all fields except password
User.findOne({ email: email }, '-password');
2. Projection by passing projection
property:
// find user and return just _id field
User.findOne({ email: email }, {
projection: { _id: 1 }
});
3. Using .select
method:
// find user and return just _id and name field
User.findOne({ email: email }).select('name');
// find user and return all fields except _id
User.findOne({ email: email }).select({ _id: 0 });
You can do the same with find
and findById
methods too.
You use projection. The first example in the mongoose query docs has a projection operation tucked in.
NB: not real code b/c I highlighted the important bits with triple stars
// find each person with a last name matching 'Ghost', ***selecting the `name` and `occupation` fields***
Person.findOne({ 'name.last': 'Ghost' }, ***'name occupation'***, function (err, person) {
if (err) return handleError(err);
console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})
The Person
schema isn't specified but I think the example is clear enough.
MyModel.find({name: "john" }, 'name age address', function(err, docs) {
console.log(docs);
});
This will return fields - name, age and address only.