Mongoose select fields to return from findOneAndUpdate

Viewed 19963

Using Mongoose in Nodejs you can return some fields using find. eg.

User.findOne({_id:'132324'}, {first_name:1, last_name:1}).exec...

but I can't seem to figure out how to return certain fields using findOneAndUpdate.

User.findOneAndUpdate({_id:'132324'}, {$set : {..bla bla}}, {first_name:1, last_name:1}).exec....

Has anyone achieved this before? I can't find it in the documentation.

7 Answers

It seems the syntax for findByIdAndUpdate has changed a little.

Its takes the form of Model.findByIdAndUpdate(query, update, options, (optional callback))

According to the docs, to specify which fields are returned you have to specify them in the options parameter. so, using the above example it would be:

User.findOneAndUpdate(
  {id},  //query
  { $set: { "fieldToBeChanged": "update" } },  //update
  {new:true, select: "fieldIWant anotherFieldIWant"}, //options
})

The new:true options is not necessary. If omitted mongoose defaults to returning the document before the updates were applied. Set to true and it will return the document after the updates have been made.

We can exclude any field while using mongoose update function findByIdAndUpdate with the help of select function,please have a look at the following code it will exclude password and __v from the Update response

User.findByIdAndUpdate({ _id: req.userData.UserId },req.body,{new: true}).select({Password: 0, __v: 0 })
    .exec()
    .then(result => {})

Try this:

User.findOneAndUpdate({_id:'132324'}, {update: '1235'}, {new: true}).select({ _id: 0 })

The select() will exclude the _id field from the result.

For MongoDb version 3.2+

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

For MongoDB version: 4.0.2, mongoose version: 5.13.7:

userModel.findOneAndUpdate({_id:'132324'},{$set: 
{"first_name":"user","last_name":"one"}}, 
{new:true,select:{first_name:1, last_name:1}},(err,data)=>{}
Related