【问题标题】:Meter push new object to array in collection仪表将新对象推送到集合中的数组
【发布时间】:2017-08-03 06:37:19
【问题描述】:

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

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

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 数组在创建新游戏时对其进行排序。添加第一个玩家时会出现问题吗?

我们将不胜感激。

【问题讨论】:

  • 这些天我遇到了同样的问题。我设法通过使用defaultValue而不是autoValue来完成。如果你想要的只是初始化属性,那么 defautValue 就是你想要的。

标签: javascript mongodb meteor meteor-collection2


【解决方案1】:

已编辑: @Logiwan992 尝试使用 defaultValue 而不是 autoValue。我相信您正在使用 autoValue 来设置 players 的值,因此它不是未定义的。但是通过您的实施,当您的文档有更新时, autoValue 将运行。

defaultValue 将在第一次创建文档时运行。但如果您仍然选择使用autoValue,您可能还需要检查它是否是更新并返回undefine。像这样

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

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

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

【讨论】:

  • 一个简短的解释为什么他应该尝试使用它会成为一个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 2018-09-23
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多