【问题标题】:meteor array $addToSet not adding any items流星数组 $addToSet 不添加任何项目
【发布时间】:2016-07-12 01:01:53
【问题描述】:

我正在尝试使用 $addToSet 将乐器添加到流星中的 Profiles 集合中。该代码在 mongo 中有效,但在流星方法调用中无效。我可以使用 $set 更新所有其他字段而不会出现任何问题,因此我知道这是在找到正确的用户。

updateInstruments(instruments) {
if (!this.userId) {
  throw new Meteor.Error('not-logged-in',
    'Must be logged in to update last name.');
}

check(instruments, String);

if (instruments.length === 0) {
  throw Meteor.Error('instruments-required', 'Must provide at least one instrument.');
}

let instrArray = instruments.split(',');
instrArray.forEach(function(instrument){
  instrument = instrument.trim();
  Profiles.update({ userId: this.userId }, { $addToSet: { instruments: instrument } });
});

},

我什至尝试过:

Profiles.update({ userId: this.userId }, { $addToSet: { instruments: {$each: [instrument] } }});

还有:

Profiles.update({ userId: this.userId }, { $addToSet: { instruments: [instrument]  }});

我也尝试过 $push ,但那里也没有发生任何事情。流星中有某种错误吗?我需要配置其他设置以允许更新数组吗?

更新: 根据请求,这是客户端代码:

updateInstruments() {
   if (_.isEmpty(this.data.instruments)) return;
      var self = this;
      let instruments = this.data.instruments;
      this.callMethod('updateInstruments', instruments, (err) => {
         if (err) return this.handleError(err);
      });
}

谢谢!

【问题讨论】:

  • 能否也包含您的客户端代码?这可能是您如何从客户端传递“仪器”并拆分、修剪造成的问题。

标签: mongodb meteor


【解决方案1】:

我发现了这个问题。我忘记了内联'instrArray.forEach'函数中'this'的范围发生了变化,使得this.userId'undefined'。 Profiles 集合找不到记录。我更改了以下代码:

let instrArray = instruments.split(',');
instrArray.forEach(function(instrument){
  instrument = instrument.trim();
  Profiles.update({ userId: this.userId }, { $addToSet: { instruments: instrument } });
});

到:

let userId = this.userId;
let instrArray = instruments.split(',');
instrArray.forEach(function(instrument){
    instrument = instrument.trim();
    Profiles.update({ userId: userId }, { $addToSet: { instruments: instrument }     });
});

感谢大家查看我的代码!

【讨论】:

    【解决方案2】:

    您的查询对我来说似乎很好。只要您在服务器上执行此操作,您就不需要配置任何东西。不是 Meteor 中的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 2021-08-27
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      相关资源
      最近更新 更多