簡體   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