I am trying to update a certain location only if its a status: 0 or status 2. Do not update if status is 1. I only have one copy of that location.
Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.update, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
Property.findOneAndUpdate({ status: 2, location: req.body.update.location }, req.body.update, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
However, the above code is updating the property even when the status is 1.
Property.find({location: req.body.update.location}, (err, Propertyz) => {
myProperty = Propertyz
console.log(myProperty[0].status)
if(myProperty[0].status != 1) { // returns and doesn't update if true
console.log("updating")
Property.findOneAndUpdate({ location: req.body.update.location }, req.body.update, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
}
else {
console.log("rejecting")
return res.json({ success: true });
}
})
I changed it to this and it works, but I don't understand why the previous was not working or if there was a way to condense the two previous functions into one.
Property.findOneAndUpdate({ $or: [{ status: 0, status: 2 }] }, { location: req.body.update.location }, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
You can update it using one findOneAndUpdate function, add $or operator on your query. https://docs.mongodb.com/manual/reference/operator/query/or/ . This code below search documents that has status 2 or 0.
Property.findOneAndUpdate({ $or: [{status: 2}, {status: 0}], location: req.body.update.location }, req.body.update, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, { $set:req.body.update} , err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
Property.findOneAndUpdate({ status: 2, location: req.body.update.location }, { $set:req.body.update} , err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.