Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable with mongodb dotnotation

I want to increase a field inside an object object inside a mongodb document by 1.

  var stuffID = 5
  collection.update({
    "id": id,
  },
  {
    '$inc': {
      'stuff.stuffID': 1
    }
  },
  function(err, doc) {
    res.end('done');
  });

I need to make that stuffID a variable. Any way to do that? Thanks.

This is using node-mongodb-native if that helps.

If you're voting to close can you explain what it is you don't understand?

like image 905
Harry Avatar asked Jul 15 '11 03:07

Harry


People also ask

What is the use of the dot notation in MongoDB?

Dot Notation. MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

How do I declare a variable in MongoDB?

Set variable value in MongoDB save() method Use db. yourCollectionName. save(yourVariableName) to set variable value, wherein “yourVariableName” is your variable.


1 Answers

You need to create your variably-keyed object separately, because JS before ES2015 doesn't permit anything other than constant strings in object literal syntax:

var stuffID = 5
var stuff = {};                 // create an empty object
stuff['stuff.' + stuffID] = 1;  // and then populate the variable key

collection.update({
    "id": id,
}, {
    "$inc": stuff               // pass the object from above here
}, ...);

EDIT in ES2015, it's now possible to use an expression as a key in an object literal, using [expr]: value syntax, and in this case also using ES2015 backtick string interpolation:

var stuffID = 5;
collection.update({
    "id": id,
}, {
    "$inc": {
        [`stuff.${stuffID}`]: 1
    }
}, ...);

The code above works in Node.js v4+

like image 54
Alnitak Avatar answered Oct 03 '22 05:10

Alnitak