当更改嵌入式数组对象时,猫鼬实例.save()无法正常工作 [英] Mongoose instance .save() not working when embedded array object changed

查看:72
本文介绍了当更改嵌入式数组对象时,猫鼬实例.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);

内部发布请求,这里req是发布请求的请求对象. 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.

推荐答案

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

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.

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

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