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

标签 javascript node.js mongodb

在使用 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/

相关文章:

javascript - InternJs,如何在命令行上设置基本路径?

javascript - 我可以在 mongo 查询中索引对象吗?

php - 安装 PHP 7 MongoDB 客户端/驱动程序?

javascript - 与 Ember.js 的部分静态属性绑定(bind)?

javascript - 如何使用 Mongoose 更新 Node 中的内部文档

javascript - 自动完成完成后隐藏输入字段

javascript - Meteorjs 集合通过 $where 查找

javascript - 从 jquery 中的动态内容捕获所有音频结束事件

javascript - d3 更改 x 轴时间仅勾选整年和整月

javascript - 替换数据属性html