如何在mongodb-native findAndModify中将变量用作字段名?

Tim*_*imo 6 javascript mongodb node.js

在这个使用mongodb-native驱动程序的代码中,我想增加我在单独变量中指定的字段的值.问题是$ inc子句中的字段名称在这种情况下将是"变量",而不是变量的内容.在查询部分中,所选变量按预期工作并找到正确的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) { /* ... */ }
);
Run Code Online (Sandbox Code Playgroud)

我应该如何做到这样,而不是"变量"这个词会有变量的内容?

Men*_*ual 13

将另一个变量的键设置为其值,并将其作为对象传递.附注行动:

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} }
Run Code Online (Sandbox Code Playgroud)