WillMcavoy WillMcavoy - 1 month ago 12x
Node.js Question

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

I have this data in mongodb:

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

I want to retrieve the data querying on a fieldname passed as a variable.

Following does not work:

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

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


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.