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.
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
api.abc.com/api/accept/5cfe4dd898fd225ef1cabdsd
Usually, we can update a single record in multiple ways
new
, if it is true it will return an updated record in the response. 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);
});
«Object|Number|String»
value of _id to query. So here, directly we can pass req.params.id
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);
})
Although you don't have to pass id
in the form of an object it seems the culprit is in req.params.uid
.
Double-check if uid
is really set on the req.params
and it's correct in a sense that it points to a document in your collection.
For the moment that's the only obvious reason that explains why you get null
back.
You can check that through mongo shell using db.collection.find(<query>)
.
Your usage of findByIdAndUpdate
doesn't seem to be correct, the first argument is supposed to be an id (mongodb object ID or just a string) instead of an object. I would try this first
this._model.findByIdAndUpdate(req.params.uid, updatevalue, options, (err, obj) => {
if (err) {
res.send(err);
}
else {
res.send(obj);
}
});
Alternatively, if you want to use query
as the filter in your code, then you can use findOneAndUpdate
instead. Detailed doc is here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With