无法更新mongoose模型

cyb*_*bat 17 javascript mongoose node.js

我有一个令人困惑的奇怪问题.我有一个模特:

var Model = new Schema({
    name: String,
    variations: Array
});
Run Code Online (Sandbox Code Playgroud)

变体条目如下所示:

[ {code: '', price: '' }, {code: '', price: '' }]
Run Code Online (Sandbox Code Playgroud)

我需要添加一个新字段 - 比如"color".所以我这样做是批量更新:

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

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

Joh*_*yHK 31

当您修改无类型Array字段的内容时variations,您需要通过调用markModified(path)已修改的文档通知Mongoose您已更改其值,否则后续save()调用将不会保存它.查看文档.

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