I am trying to do a simple update, but it doesnt work when I use a variable for the field I want to change.
This works
var update = {"$inc": {"racesWon" : 1}}
User.findOneAndUpdate({
username: req.body.username
}, update, {}, callback)
Now I have a switch like this
var resultToUpdate = ""
switch (req.body.result) {
case 1:
resultToUpdate = "racesWon";
break;
case 2:
resultToUpdate = "racesSecond";
break;
case 3:
resultToUpdate = "racesThird";
break;
}
I want to use the resultToUpdate variable to change what is updated, but it doesn't work. I've been up all night and I cant see what is wrong
var update = {"$inc": { resultToUpdate : 1}}
User.findOneAndUpdate({
username: req.body.username
}, update, {}, callback)
edit: it's not the same issue as marked. The problem is - Why is the variable not working in the mongoose update? Does it have to be literally quotes "" and not a variable?
Solved it doing this.
switch (req.body.result) {
case 1:
update = {"$inc": {racesWon: 1}};
break;
case 2:
update = {"$inc": {racesSecond: 1}};
break;
case 3:
update = {"$inc": {racesThird: 1}};
break;
}
Edit: old way doesnt work because - You can't initialize objects with 'dynamic' keys.