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.

Leave a Comment