Mongoose select fields to return from findOneAndUpdate

后端 未结 4 1328
别那么骄傲
别那么骄傲 2020-12-03 08:11

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

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

but

4条回答
  •  一整个雨季
    2020-12-03 08:29

    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.

提交回复
热议问题