MichaelGofron
MichaelGofron

Reputation: 1410

Pushing into an array inside of a mongoose object

I am using mongoose to push a player into a players array in mongoose when a player joins the game. I am getting the following error: "Can't canonicalize query: BadValue unknown top level operator: $push"

It appears to be a problem with how I'm formatting the $push but I tried to follow this answer and am not sure how my code differs from their implementation: pushing object into array schema in Mongoose

I have the following schema:

var GameSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.Mixed,
players: [{
  username: String,
  currentRound: Number
}],
// the number represents the qNumber in the questionData.js
// and also the round number for what the player is currently on
questions: [Number]
});

and the following update call

var Game = mongoose.model('Game', GameSchema);

var updateGame = function(req,res,next){
Game.findByIdAndUpdate(
  req.body.code,
  {$push: {"players": {username: "hardcode", currentRound: 1}}},
  {safe: true, upsert: true, new: true},
  function(err, model){
    if (err){
      console.log("ERROR: ", err);
      res.send(500, err);
    }else{
      res.status(200).send(model);
    }
  }
);
};

Upvotes: 3

Views: 3860

Answers (1)

MichaelGofron
MichaelGofron

Reputation: 1410

Argh, I always figure out the solution right after asking.

It turns out that because I override the _id key in my schema the Game.findByIdAndUpdate does not work. Instead I used the findOneAndUpdate passing in the _id key:

Game.findOneAndUpdate(
{"_id":req.body.code},
{$push: {"players": {username: "hardcode", currentRound: 1}}},
{safe: true, upsert: true, new: true},
function(err, model){
   if (err){
     console.log("ERROR: ", err);
     res.send(500, err);
   }else{
     res.status(200).send(model);
   }
  }
);

Upvotes: 4

Related Questions