简体   繁体   English

Mongoose / MongoDb FindOneAndUpdate未按预期工作

[英]Mongoose/MongoDb FindOneAndUpdate not working as expected

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. 我正在尝试仅在其状态为0或状态2时更新某个位置。如果状态为1,则不更新。我只有该位置的一个副本。

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. 但是,即使状态为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. 您可以使用一个findOneAndUpdate函数更新它,在查询中添加$或operator。 https://docs.mongodb.com/manual/reference/operator/query/or/ . https://docs.mongodb.com/manual/reference/operator/query/or/ This code below search documents that has status 2 or 0. 下面的代码搜索状态为2或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 });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM