Frage

My mongoDB document looks like this:

   {
      valOne: "one",
      valTwo: "two",
      valThree: {
                  threeOne: 0,
                  threeTwo: 0
                }
    }

i would like to increment either "threeOne" or "threeTwo" depending on the user request.

My code so far:

var whichFieldToUpdate = request.body.field; //can be either threeOne or threeTwo
var id = new BSON.ObjectID(request.body.id); //contains document id

db.collection('name').update({_id: id}, {$inc: { ?????? } },
  function(err, result) {

});

???? should be something like this: {$inc: {valThree: {whichFieldToUpdate : 1 } }

War es hilfreich?

Lösung

var field = 'valThree.' + request.body.field;
var inc =  {};
inc[field] = 1;

db.collection('name').update({_id: id}, {$inc: inc } },
  function(err, result) {

});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top