无法更新猫鼬模型 [英] Unable to update mongoose model

查看:35
本文介绍了无法更新猫鼬模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题让我感到困惑.我有一个模型:

I have a weird issue that is baffling me. I have a model:

var Model = new Schema({
    name: String,
    variations: Array
});

变体条目如下所示:

[ {code: '', price: '' }, {code: '', price: '' }]

我需要添加一个新字段 - 说颜色".所以我这样做是为了批量更新:

I need to add a new field - say "color". So I am doing this to batch update:

Model.find().exec(function(err, products) {
    if (!err) {
        products.forEach(function(p) {
            for(var i = p.variations.length - 1; i >= 0; i--) {
                p.variations[i]['color'] = 'red';
                // This shows all existing variations 
                // with the new color feed - correct
                console.log(p.variations[i]);
            }
            p.save(function(err) {
                if (!err) {
                    console.log("Success");
                } else {
                    console.log(err);
                }
            });
        });     
    }
});

但是颜色"字段未设置 - 如果我再次检查并注释掉 p.variations[i]['color'] = 'red'; 行,那么它不会展示.我似乎无法弄清楚为什么要这样做.我有一个正确触发的 onSave 事件,因此它正在保存.我也没有对变体结构进行任何检查 - 即没有只允许代码和价格的代码.我显然错过了一些东西,但几个小时后,我的想法用完了.

However the "color" field is not set - if I go through again and comment out the p.variations[i]['color'] = 'red'; line then it does not show. I can't seem to figure out why it's doing this. I have an onSave event that is triggered correctly so it's saving. I also do not have any check on the variations structure - i.e. there is no code that only allows code and price. I'm obviously missing something but after a couple of hours I ran out of ideas.

推荐答案

当你修改一个像 variations 这样的非类型化 Array 字段的内容时,你需要通知 Mongoose您通过在修改后的文档上调用 markModified(path) 更改了它的值,否则后续的 save() 调用将不会保存它.查看文档.

When you modify the contents of an untyped Array field like variations, you need to notify Mongoose that you've changed its value by calling markModified(path) on the modified document or a subsequent save() call won't save it. See docs.

  for(var i = p.variations.length - 1; i >=0; i--) {
    p.variations[i]['color'] = 'red';
  }
  p.markModified('variations');
  p.save(function(err) { ...

这篇关于无法更新猫鼬模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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