node.js 如何在 mongodb-native findOne() 中使用变量作为字段名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17039018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:45:33  来源:igfitidea点击:

How to use a variable as a field name in mongodb-native findOne()?

node.jsmongodbexpress

提问by WillMcavoy

I have this data in mongodb:

我在 mongodb 中有这些数据:

{  
    "name": "Amey",
    "country": "India",
    "region": "Dhule,Maharashtra"
}

and I want to retrieve the data while passing a field name as a variable in query.

我想在将字段名称作为查询中的变量传递时检索数据。

Following does not work:

以下不起作用:

var name = req.params.name;
var value = req.params.value;
collection.findOne({name: value}, function(err, item) {
    res.send(item);
});

How can I query mongodb keeping both field name and its value dynamic?

如何查询 mongodb 保持字段名称及其值动态?

回答by maxdec

You need to set the key of the query object dynamically:

您需要动态设置查询对象的键:

var name = req.params.name;
var value = req.params.value;
var query = {};
query[name] = value;
collection.findOne(query, function (err, item) { ... });

When you do {name: value}, the key is the string 'name'and not the value of the variable name.

当你这样做时{name: value},关键是字符串'name'而不是变量的值name

回答by KiwenLau

Just put the variable in []

只需将变量放入 []

var name=req.params.name;
var value = req.params.value;
collection.findOne({[name]:value}, function(err, item) {
res.send(item);
});

回答by hydrix

I'd like to clarify that if you're trying to make a query concerning a nested field only (not its value), like if you want to query the field "name" from this document:

我想澄清一下,如果您试图仅对嵌套字段(而不是其值)进行查询,例如您想从本文档中查询字段“名称”:

{
    loc: [0, 3],
    unit: {
        name : "playername"
    }
}

this will work (as in my case - using update):

这将起作用(在我的情况下 - 使用更新):

mdb.cords.updateOne(
    {_id: ObjectID(someid)}, 
    {$set: {[query]: newValue}}, 
    function (err, result) {
        ...
    }
}

Simply enclosing [query]in brackets tells mongodb that it's not literal, but rather a path.

简单地[query]用括号括起来告诉 mongodb 它不是文字,而是一条路径。