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

node.jsMongodbExpress

node.js Problem Overview


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.

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?

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

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

Solution 3 - node.js

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.

Solution 4 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWillMcavoyView Question on Stackoverflow
Solution 1 - node.jsmaxdecView Answer on Stackoverflow
Solution 2 - node.jsKiwenLauView Answer on Stackoverflow
Solution 3 - node.jshydrixView Answer on Stackoverflow
Solution 4 - node.jsAnkit Kumar RajpootView Answer on Stackoverflow