如何在 mongodb-native findOne() 中使用变量作为字段名? [英] How to use a variable as a field name in mongodb-native findOne()?
本文介绍了如何在 mongodb-native findOne() 中使用变量作为字段名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 mongodb 中有这些数据:
I have this data in 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.
以下不起作用:
var name = req.params.name;
var value = req.params.value;
collection.findOne({name: value}, function(err, item) {
res.send(item);
});
如何查询 mongodb 以保持字段名称及其值动态?
How can I query mongodb keeping both field name and its value dynamic?
推荐答案
需要动态设置查询对象的key:
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) { ... });
当您执行{name: value}
时,键是字符串'name'
而不是变量name
的值.
When you do {name: value}
, the key is the string 'name'
and not the value of the variable name
.
这篇关于如何在 mongodb-native findOne() 中使用变量作为字段名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文