Mongoose select fields to return from findOneAndUpdate

From the manual, the options argument needs a "fields" key in it since there are other details such as "upsert" and "new" where this applies. In your case you also want the "new" option:

User.findOneAndUpdate(
  { "_id": "132324" },
  { "$set": { "hair_color": "yellow" } },
  {
   "fields": { "first_name":1, "last_name": 1 },
   "new": true 
  }
).exec(...)

Alternately you may use .select()

User.select({ "first_name": 1, "last_name": 1 }).findOneAndUpdate(
  { "_id": "132324" },
  { "$set": { "hair_color": "yellow" } },
  { "new": true }
).exec(...)

Noting that without "new": true the document returned is in the state before the modification of the update was processed. Some times this is what you mean, but most of the time you really want the modified document.

Leave a Comment