Eu tenho estes dados no mongodb:
{
"name": "Amey",
"country": "India",
"region": "Dhule,Maharashtra"
}
e eu quero recuperar os dados ao passar um nome de campo como uma variável na consulta.
O que se segue não funciona:
var name = req.params.name;
var value = req.params.value;
collection.findOne({name: value}, function(err, item) {
res.send(item);
});
Como posso consultar o mongodb mantendo o nome do campo e seu valor dinâmicos?
Respostas:
Você precisa definir a chave do objeto de consulta dinamicamente:
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 variablename
.fonte
value
by your query like{ $gt: 50 }
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); });
fonte
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.fonte
use like this if the object is nested.
Direct Object:-
var name=req.params.name; var value = req.params.value; collection.findOne({[name]:value}, function(err, item) { res.send(item); });
An object is nested:-
var surname=req.params.surname; var value = req.params.value; var condition = `name.${surname}` collection.findOne({[condition]:value}, function(err, item) { res.send(item); });
fonte
'name.${surname}'
but for variable we don't use ', thanks