node.jsmongodbmongojs

Pushing new value to array in MongoDB document with NodeJS


I have a MongoDB collection with documents that look as follows:

{
    "id": 51584,
    "tracks": [],
    "_id": {
        "$oid": "ab5a7... some id ...cc81da0"
    }
}

I want to push a single track into the array, so I try the following NodeJS code:

function addTrack(post,callback){
    var partyId = post['partyId'], trackId = post['trackId'];
    // I checked here that partyId and trackId are valid vars.
    db.db_name.update({id: partyId}, { $push: { tracks: [trackId] } }, function(err, added) {
      if( err || !added ) {
        console.log("Track not added.");
        callback(null,added);
      }
      else {
        console.log("Track added to party with id: "+partyId);
        callback(null,added);
        }
    });
}

This returns successfully with the callback that the track was added. However, when I inspect the database manually it is not updated and the array tracks is still empty. I've tried a lot of different things for the tracks element to be pushed (ie. turning it into an array etc.) but no luck so far.

PS: Perhaps I should note that I'm using MongoLab to host the database.

Any help would be most welcome.


Solution

  • I found my problem, in the addTrack update({id: partyId},.. method partyId was not a string so it didn't find any docs to push to. Thanks to SudoGetBeer for leading me to the solution.