【问题标题】:How to use a variable as a field name in mongodb-native findAndModify?如何在 mongodb-native findAndModify 中使用变量作为字段名?
【发布时间】:2014-03-10 14:49:57
【问题描述】:

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

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

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    将另一个变量的键设置为其值并将其作为对象传递。 动作说明

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

    【讨论】:

    • 谢谢。这正是我所关心的。
    猜你喜欢
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多