我正在尝试通过推送到集合中已经存在的数组来更新集合。
这是我尝试运行的更新功能:
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
forplayers
数组在创建新游戏时对其进行初始化。这可能是添加第一个玩家时的问题吗?
一些帮助将不胜感激。
编辑: @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: [], },
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句