在使用 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) { /* ... */ }
);
我应该怎么做才能让变量的内容代替“变量”这个词?
最佳答案
将另一个变量的键设置为其值并将其作为对象传递。 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} }
关于javascript - 如何在 mongodb-native findAndModify 中使用变量作为字段名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11133912/