Question:
I have wrote a update query which will find the record by _id and update. This code is completely working fine until If I add a new record in that collection. If add a record and do a query it goes to success part but returns null instead of the data. But when I restart the code and try same operation, it’s working fine. My method is PUT.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
accept = (req, res) => { var query = { _id: req.params.uid }; var updatevalue = { $set: { status: 3 } }; var options = { new: true } this._model.findByIdAndUpdate(query, updatevalue, options, (err, obj) => { if (err) { res.send(err); } else { res.send(obj); } }); |
}
Request
1 2 |
api.abc.com/api/accept/5cfe4dd898fd225ef1cabdsd |
Answer:
Usually, we can update a single record in multiple ways
- findOneAndUpdate() method is used for update a record in collection.
It is okay to use this method, instead of manually finding the record and then updating it.
This method works really faster than the manual method.
It has an option flagnew
, if it is true it will return an updated record in the response.
1 2 3 4 5 6 7 8 9 10 |
User.findOneAndUpdate({_id: id},{$set:{name:user.name}},{new:true}).then((docs)=>{ if(docs) { resolve({success:true,data:docs}); } else { reject({success:false,data:"no such user exist"}); } }).catch((err)=>{ reject(err); }); |
- findByIdAndUpdate() method is used to update record based on Id.
Where we can pass the id as«Object|Number|String»
value of _id to query. So here, directly we can passreq.params.id
1 2 3 4 5 6 7 8 9 10 11 |
User.findByIdAndUpdate(req.params.id,{$set:{name:user.name}},{new:true}).then((docs)=>{ if(docs) { resolve({success:true,data:docs}); } else { reject({success:false,data:"no such user exist"}); } }).catch((err)=>{ reject(err); }) |