Mongoose select fields to return from findOneAndUpdate

后端 未结 4 1316
别那么骄傲
别那么骄傲 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:18

    Use option {new: true} in findOneAndUpdate (default: false)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 08:33

    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.

    0 讨论(0)
  • 2020-12-03 08:35

    For MongoDb version 3.2+

    User.findOneAndUpdate(
      { "_id": "132324" },
      { "$set": { "hair_color": "yellow" } },
      {
       "projected": { "first_name":1, "last_name": 1 },
       "returnNewDocument": true 
      }
    )...
    
    0 讨论(0)
提交回复
热议问题