且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当更改嵌入式数组对象时,猫鼬实例.save()无法正常工作

更新时间:2023-09-17 09:44:58

问题是猫鼬不知道您的数组是否被修改.

The problem is that mongoose don't knwo your array is modified.

您可以使用2种解决方案:

You can use 2 solutions :

此功能会将嵌入的元素标记为已修改,并强制重新保存它. 它会告诉猫鼬重新保存此元素.

This function will mark the embedded element as modified and force a resave of it. It will tell mongoose to resave this element.

User.findById(userID).exec(function (err, doc) {
        let cardInfo = req.cardInfo
        let cardIndex = req.cardIndex
        doc["cards"][0] = cardInfo;
        console.log(doc)
/*  here I got right doc object as I requested
{
        "_id": "59f3bdd488f912234fcf06ab",
        "email": "test@gmail.com",
        "username": "test",
        "__v": 2,
        "cards": [
            {
                "testNo": "42424242424242"
            }
        ]
    }
*/
        doc.markModified('cards');
        doc.save(function (err) {
          if (err) {
            return res.json({
              success: false,
              msg: 'Card add error'
            });
          }
          res.json({
            success: true,
            msg: 'Successful updated card.'
          });
        });
})

使用完整架构.

为避免markModified技巧,应在架构中描述卡的内容.这样,猫鼬将能够确定是否需要保存该字段.

Use a full schema.

To avoid the markModified trick, you should describe the content of cards in your schema. This way mongoose will be able to determine if it needs to save the field or not.

这是正确声明架构的方法:

Here is the way to declare your schema properly :

const CardSchema = new Schema({
  testNo: String,
});

var UserSchema = new Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    cards: [CardSchema]
});
module.exports = mongoose.model('User', UserSchema);

这样,猫鼬将能够检测卡中的值是否已更改,并且仅保存修改后的项目.

This way, mongoose will be able to detect if a value inside cards changed and save only the modified item.

如果可以做到(静态模式),显然这是个好方法.

If you can do it (static schema), this is clearly the good way to do it.