6

在这段使用 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) { /* ... */ }
);

我应该怎么做才能让变量的内容代替“变量”这个词?

4

1 回答 1

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} }
于 2012-06-21T08:09:03.020 回答