簡體   English   中英

NodeJS & Mongoose,更新對象數組中的值不起作用

[英]NodeJS & Mongoose, update values in array of objects not working

我正在努力使用貓鼬函數findByIdAndUpdate()更新我的UserSchema一些特定數組。

這是我的UserSchema

const UserSchema = new mongoose.Schema({
    mail: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    friends: [{id: String}],
    prot: [{
        id: String,
        admin: Boolean,
    }]
});

我只想更新prot元素,這就是我想要的方式:

User.findByIdAndUpdate(req.body.userId, {
        $set: { prot: [{ id: req.body.lockId, admin: req.body.isAdmin }] }, function(err, user) {
            if (err) {
                return res.status(500).send({
                    message: err.message || "Some error occured while updating user"
                });
            }
            if (!user) {
                return res.status(404).send({
                    message: "User not found"
                });
            }

            return res.status(200).send(user);
        }
    })

但是當我嘗試通過Postman發送請求時,我沒有收到響應或錯誤..

FindByIdAndUpdate默認不返回更新的文檔,您應該添加選項{new:true} 你也有混合括號。 像下面這樣做:

User.findByIdAndUpdate(
    req.body.userId, 
    {
       $set: { 
          prot: [{ 
                id: req.body.lockId, 
                admin: req.body.isAdmin 
          }] 
       }
   }, 
   { new: true },
   function(err, user) {
        if (err) {
            return res.status(500).send({
                message: err.message || "Some error occured while updating user"
            });
        }
        if (!user) {
            return res.status(404).send({
                message: "User not found"
            });
        }

        return res.status(200).send(user);
    }
);

如果要更新對象數組中的特定記錄。 你可以這樣做。

  User.update(
      { _id: req.body.userId, 
        prot: 
            { $elemMatch: { id: req.body.lockId }}
      },
      { $set: 
            { prot: { admin: req.body.isAdmin }
      }
   },(error,result)=>{
      if(error){ 
         //handle error
      }
      console.log(result);
    } 
    )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM