【问题标题】:Unable to update array fields in mongoosejs无法更新 mongoosejs 中的数组字段
【发布时间】:2012-11-07 21:19:28
【问题描述】:

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

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

如果同步标志为真,我会使用保存后中间件来更新第 3 方站点。在该操作返回时,我更新了价格数组并将同步设置为 false,这样它就不会导致无限循环。

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 = [];

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

有什么想法吗?

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    如果您未指定数组字段中的架构(如在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();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-01-07
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多