i am trying to update a document in mongo db with nodejs native driver.
initially it was inserted like:
matches {
_id:2001,
requester:"MITH",
accepter:"NIKK",
toss:"MITH",
bat:"NIKK",
scores:{"MITH":220},
status:0,
won:"MITH"
}
now i need to update the document where i need to insert a new element "NIKK":198 to scores object to make it scores:{"MITH":220,"NIKK":198}
problem is the key comes in a variable only. and when i update it is not updating
Below is the code with which i am trying
var _jsonMatch = {status:4};
var _scorepush = {}
_scorepush[variablevalue] = 198; // variablevalue in reference above is NIKK
var data = {"$set": _jsonMatch,"$push": {"scores":_scorepush} }
mith.findAndModify({_id:mith.db.bson_serializer.ObjectID.createFromHexString(matchId)},
[],
data,
{ upsert: true,new:true },
function(error, match){
if( error ) callback(error);
else callback(null, match);
});
EDIT :
I tried $addToSet instead of $push and i got the below error in callback with data undefined.
{ [MongoError: Cannot apply $addToSet modifier to non-array] name: 'MongoError', lastErrorObject: { err: 'Cannot apply $addToSet modifier to non-array', code: 12591, n: 0, connectionId: 56, ok: 1 }, errmsg: 'Cannot apply $addToSet modifier to non-array', ok: 0 } undefined