无法更新mongoosejs中的数组字段

时间:2012-11-07 05:24:06

标签: javascript node.js mongoose

我有一个奇怪的问题我无法解决。我有一个Mongoose架构:

Product = new Schema({
  title: {
     type: String
  },
  prices: {
     type: Array
  },
  sync: {
     type: Boolean
  }
  ...

如果sync标志为true,我使用post save中间件更新第三方站点。在返回该操作时,我更新了价格数组并将同步设置为假,这样就不会导致无限循环。

Product.post('save', function () { 
    if(this.sync) {
        this.title = "HELLO";
        this.prices[0].retail = '24';
        this.sync = false;
        this.save();
    }
});

如果我执行上述操作,则标题和同步字段会更改,但不会更改价格数组。实际上我无法更新架构中的任何数组。在上面的示例中,价格数组包含大约10个条目 - 每个条目包含许多字段,包括零售字段。我也尝试过添加到那个数组:

this.prices.push({ retail: "10 });

除了重新启动数组:

this.prices = [];

无论我做什么都没有效果。但是,可以更新任何非数组字段。

任何想法发生了什么?

1 个答案:

答案 0 :(得分:2)

如果您没有在数组字段中指定架构(如prices),则Mongoose会将其视为Mixed字段,您必须通知Mongoose您所做的任何更改它让Mongoose知道要保存它。文档here

所以你的代码应该改为:

Product.post('save', function () { 
    if(this.sync) {
        this.title = "HELLO";
        this.prices[0].retail = '24';
        this.markModified('prices');
        this.sync = false;
        this.save();
    }
});