0

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.

Tom S
  • 174
  • 14
  • It would be helpful if you explained what you mean by "it doesn't work". Does the result not match what you expected, does it gives an error, or what? – Bernardo Sulzbach Apr 05 '16 at 06:16
  • The record is not updated in mongo, there is no error. If I put this { resultToUpdate : 1} it doesn't update anything. If I put this { "racesWon" : 1} it does update the field – Tom S Apr 05 '16 at 06:30
  • @TomS In JavaScript `{resultToUpdate: 1}` is **exactly the same thing as** `{"resultToUpdate": 1}`, e.g. even in the first, you do not have a variable reference. This is a very basic JavaScript question. – Antti Haapala -- Слава Україні Apr 05 '16 at 07:20
  • 1
    Better duplicate: http://stackoverflow.com/questions/10640159/key-for-javascript-dictionary-is-not-stored-as-value-but-as-variable-name – Antti Haapala -- Слава Україні Apr 05 '16 at 07:22
  • Ok thanks I understand using that duplicate. 'You can't initialize objects with 'dynamic' keys.' :) Solved it anyhow cheers – Tom S Apr 06 '16 at 12:29

0 Answers0