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

Web*_*per 6 arrays save mongodb node.js

我正在使用Mongoose npm模块来管理mongodb。这是我将要更新的mongodb集合的架构。

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

在发布请求中,这里req是发布请求的请求对象。res是响应对象。

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.save(function (err) {
          if (err) {
            return res.json({
              success: false,
              msg: 'Card add error'
            });
          }
          res.json({
            success: true,
            msg: 'Successful updated card.'
          });
        });
})
Run Code Online (Sandbox Code Playgroud)

我收到消息“更新卡成功。”,但实际上,它没有保存。如何解决。谢谢。

Jul*_*SIN 9

问题是猫鼬不知道你的数组被修改了。

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

markModified

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

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.'
          });
        });
})
Run Code Online (Sandbox Code Playgroud)

使用完整架构。

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

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

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);
Run Code Online (Sandbox Code Playgroud)

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

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