繁体   English   中英

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

[英]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数组的autoValueautoValue进行初始化。 添加第一个播放器时可能会出现问题吗?

一些帮助,将不胜感激。

编辑: @ 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: [], },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM