繁体   English   中英

Mongoose / MongoDb FindOneAndUpdate未按预期工作

[英]Mongoose/MongoDb FindOneAndUpdate not working as expected

我正在尝试仅在其状态为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 });
});

但是,即使状态为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 });
    }
})

我把它改成了它并且它可以工作,但是我不明白为什么之前没有工作或者是否有办法将前两个函数压缩成一个。

      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 });
      });

您可以使用一个findOneAndUpdate函数更新它,在查询中添加$或operator。 https://docs.mongodb.com/manual/reference/operator/query/or/ 下面的代码搜索状态为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