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

javascript - How to use a variable as a field name in mongodb-native findAndModify? - Stack Overflow

programmeradmin3浏览0评论

In this code that uses the mongodb-native driver I'd like to increase the value of the field which I specify in a separate variable. The problem is that the field name in the $inc clause will be 'variable' in this case, not the contents of the variable. In the query part the variable selected works as expected and finds the correct id.

var selected = 'id_of_the_selected_one';
var variable = 'some_string';
collection.findAndModify(
     {_id : selected}, 
     {},
     {$inc : {variable : 1}},
     {new : true, upsert : true},
     function(err, autoincrement) { /* ... */ }
);

How should I do it so that instead of the word 'variable' there will be the contents of the variable?

In this code that uses the mongodb-native driver I'd like to increase the value of the field which I specify in a separate variable. The problem is that the field name in the $inc clause will be 'variable' in this case, not the contents of the variable. In the query part the variable selected works as expected and finds the correct id.

var selected = 'id_of_the_selected_one';
var variable = 'some_string';
collection.findAndModify(
     {_id : selected}, 
     {},
     {$inc : {variable : 1}},
     {new : true, upsert : true},
     function(err, autoincrement) { /* ... */ }
);

How should I do it so that instead of the word 'variable' there will be the contents of the variable?

Share Improve this question edited Mar 10, 2014 at 6:49 Dan Dascalescu 152k64 gold badges332 silver badges419 bronze badges asked Jun 21, 2012 at 8:02 Timo AlbertTimo Albert 6551 gold badge6 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

Set the key of another variable to its value and pass that as an object. Note of action:

var selected = 'id_of_the_selected_one';
var variable = 'some_string';
var action = {};
action[variable] = 1; // the value

collection.findAndModify(
    {_id : selected}, 
    {}, 
    {$inc : action}, 
    {new : true, upsert : true}, 
    function(err, autoincrement) { /* ... */ }
); // Same as {$inc: {'some_string': 1} }
发布评论

评论列表(0)

  1. 暂无评论