简体   繁体   English

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

[英]Meter push new object to array in collection

I am trying to update a collection by pushing to an already existing array in the collection. 我正在尝试通过推送到集合中已经存在的数组来更新集合。

Here is the update function I am trying to run: 这是我尝试运行的更新功能:

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

Here is the error I am getting in the console: 这是我在控制台中遇到的错误:

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

Relevant schemas: 相关架构:

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

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

I am using the autoValue for the players array to sort of initialize it when a new game is created. 创建新游戏时,我使用的autoValue用于players数组的autoValueautoValue进行初始化。 Could this be a problem for when the first player is added? 添加第一个播放器时可能会出现问题吗?

Some help would be appreciated. 一些帮助,将不胜感激。

Edited: @Logiwan992 try using defaultValue instead of autoValue.I believe you're using autoValue to set the value of players so it isn't undefined. 编辑: @ Logiwan992尝试使用defaultValue而不是autoValue。我相信您正在使用autoValue设置players的值,因此它不是不确定的。 But with your implementation, autoValue would run when there is an update on your document. 但是通过您的实现,当文档上有更新时,autoValue将运行。

defaultValue would run when the document is created first. defaultValue将在首次创建文档时运行。 But if you still choose to use autoValue , you may also want to check if it's an update and return undefine . 但是,如果您仍然选择使用autoValue ,则可能还需要检查它是否为更新,并返回undefine As in this 像这样

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

Returning undefined would ensure the new update value is used. 返回undefined将确保使用新的更新值。 My recommendation though is to use 我的建议虽然是使用

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

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

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