javascriptmongodbmeteormeteor-collection2

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. Could this be a problem for when the first player is added?

Some help would be appreciated.


Solution

  • 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. But with your implementation, autoValue would run when there is an update on your document.

    defaultValue would run when the document is created first. But if you still choose to use autoValue, you may also want to check if it's an update and return 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. My recommendation though is to use

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