仪表将新对象推送到集合中的数组

Meter push new object to array in collection

我正在尝试通过推送到集合中已存在的数组来更新集合。

这是我正在尝试的更新功能 运行:

Games.update({ _id: game._id }, {
  $push: { players: { name: playerName } },
});

这是我在控制台中遇到的错误:

update failed: MongoError: Cannot update 'players' and 'players' at the same time

相关架构:

Player = new SimpleSchema({
  name: {
    type: String,
    label: 'name',
    max: 50,
  },
});

Schemas.Game = new SimpleSchema({
  ...
  players: {
    type: [Player],
    label: 'Players',
    autoValue: function () {
      return [];
    },
  },
});

我正在使用 autoValue 作为 players 数组,以便在创建新游戏时对其进行初始化。这可能是添加第一个玩家时的问题吗?

一些帮助将不胜感激。

已编辑: @Logiwan992 尝试使用 defaultValue 而不是 autoValue.I 相信您正在使用 autoValue 来设置 players 的值,所以它不是不明确的。但是在您的实施中,当您的文档有更新时,autoValue 会 运行。

defaultValue 在首次创建文档时会 运行。但如果你仍然选择使用autoValue,你可能还想检查它是否是更新和return undefine。如此

players: { type: [Player], label: 'Players', autoValue: function () { if (this.isUpdate) { return undefined; } return []; }, },

返回 undefined 将确保使用新的更新值。 不过我的建议是使用

players: { type: [Player], label: 'Players', defaultValue: [], },