Adding (and removing) objects from Array

Hey all,

Basically I am using simple schema to define an array of users;

owns: {
    type: Array,
    label: 'People who own this game.',
    optional: true,
  },
  'owns.$': {
    type: String,
},

I have built the following methods (which I am using generically as I have other like ‘user’ based arrays) which I intend to add (or remove) the user from the chosen array - currently the methods override the entire field instead of leaving all other user and only changing the current user;

'games.addFieldArray': function gamesAddField( gam ) {
    check(gam, {
      _id: String,
      field: String,
    });

    try {
      const gameId = gam._id;
      const gamToAddField = Games.findOne({ _id: gameId });
      //let updatedArray = gamToAddField.owns.push( this.userId );//need to update "owns" with the gam.field value
      
      Games.update(gameId, { $set: { [gam.field]: this.userId } });
      return gameId;

      throw new Meteor.Error('403', 'Apologies - we had some difficulties with your request.');
    } catch (exception) {
      handleMethodException(exception);
    }
  },
  'games.removeFieldArray': function gamesRemoveField( gam ) {
    check(gam, {
      _id: String,
      field: String,
    });

    try {
      const gameId = gam._id;
      const gamToRemoveField = Games.findOne({ _id: gameId });
      //let updatedArray = gamToRemoveField.owns.arrayRemove( this.userId );//need to update "owns" with the gam.field value
      
      Games.update(gameId, { $set: { [gam.field]: '' } });//should be updatedArray
      return gameId;

      throw new Meteor.Error('403', 'Apologies - we had some difficulties with your request.');
    } catch (exception) {
      handleMethodException(exception);
    }
},

Looking forward to finding the best solution (happy for you to offer suggestions for cleaning this up if you have any too).

Use [String] as the type for owns;

owns: {
    type: [String],
    label: 'People who own this game.',
    optional: true
}

@juho, that syntax was deprecated and already removed in recent versions of simpl-schema

@auBusinessDaD to update an array in MongoDB, use $push and $pull
https://docs.mongodb.com/manual/reference/operator/update/push/

Here’s an example:

// If gam.field is an array
Games.update(gameId, { $push { [gam.field]: this.userId } });
2 Likes

Thanks @coagmano, I thought it would be something super simple like that!

Also for a string that is an id in the db (like userId) you can add the following regex option for additional checking:

'owns.$': {
    type: String,
    regEx: SimpleSchema.RegEx.Id
}
2 Likes

Thanks @storyteller, I will definitely do that!

Ah alright, good to know, thanks!

1 Like