Search code examples
node.jsmongodbmongodb-queryloopbackjs

Loopback push string to array


My question is similar to this question asked in 2016 which unfortunately does not have an accepted answer. I'm also unable to use the answer there to figure out how I need to accomplish the same.

I am basically trying to add a new item to an array in my data model.

My current data model (What I want) is like this:

{
   teamId: 'team32',
   teamName: 'Lions',
   players: ['Jack','Ryan','Sam']
}

When a new team is created, an empty array is added for 'players'. There is no model for players. It is just an array which can hold a list of players.

How do I add a new player to the list of players (Add a string to the list)? I'm also open to storing it as an object instead of string.

My Team model

{
  "name": "teams",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "teamID": {
      "type": "string",
      "required": true
    },
    "teamName": {
      "type": "string",
      "required": true
    },
    "players":{
      "type":"array",
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

team.js

var updateQuery = {players:{$addToSet:{'Mark'}}};

team.update({teamID:'teams32'},updateQuery,
     function(err,data){
         console.log(err,data,'result');
      });

$addToSet and $push have both worked for me with MongoDB with mongoose. But somehow don't seem to work on loopback. How do I go about this since $addToSet and $push are both not working for me in this case?


Solution

  • This deserves two calls but might help you:

    team.addPlayer = function (player, cb) {
        team.findOne({where: {teamID: "teams32"}}, function (err, team) {
            if (!err && team) {
                var players = [];
                if (team.players) {
                    players = team.players;
                }
                players.push(player);
                team.updateAttributes({players: players}, function(err, team) {
                    cb (err, team);
                });
            } else {
                cb (err, {});
            }
        });
    };
    
    team.remoteMethod('addPlayer', {
        accepts: {arg: 'player', type: 'string', required: true},
        returns: {arg: 'team', type: 'object'},
        http: {verb: 'put'}
    });