如何在mongodb本地findAndModify中使用变量作为字段名称? [英] How to use a variable as a field name in mongodb-native findAndModify?

查看:144
本文介绍了如何在mongodb本地findAndModify中使用变量作为字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此使用mongodb-native驱动程序的代码中,我想增加我在单独的变量中指定的字段的值.问题在于,在这种情况下,$ inc子句中的字段名称将是变量",而不是变量的内容.在查询部分中,所选变量按预期工作并找到正确的ID.

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?

推荐答案

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

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} }

这篇关于如何在mongodb本地findAndModify中使用变量作为字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆