最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - variable with mongodb dotnotation - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jul 15, 2011 at 7:17 Harry asked Jul 15, 2011 at 3:39 HarryHarry 55k76 gold badges185 silver badges270 bronze badges 2
  • In what sense do you want to "make that stuffID a variable"? – cwb Commented Jul 15, 2011 at 6:43
  • @cwb like if stuffID is actually a different value and not the string stuffID. – Harry Commented Jul 15, 2011 at 6:49
Add a ment  | 

2 Answers 2

Reset to default 18

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+

Put the variable where it says stuffID.

'stuff.' + varname: 1
发布评论

评论列表(0)

  1. 暂无评论