当嵌入式数组对象更改时,Mongoose 实例 .save() 不起作用 [英] Mongoose instance .save() not working when embedded array object changed

查看:22
本文介绍了当嵌入式数组对象更改时,Mongoose 实例 .save() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Mongoose npm module to manage mongodb. This is schema of mongodb collection what I am going to update.

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

在 post 请求中,这里 req 是 post 请求的请求对象.res 是响应对象.

inside post request, here req is request object of post request. and res is response object.

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

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

I got message 'Successful updated card.', but actually, It doesn't save. How to solve it. Thanks.

推荐答案

问题是mongoose不知道你的数组被修改了.

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

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

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 技巧,您应该在架构中描述卡片的内容.这样 mongoose 将能够确定是否需要保存该字段.

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

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

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.

这篇关于当嵌入式数组对象更改时,Mongoose 实例 .save() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆