94

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?

1
  • Just found this post. I think that this is really insecure. Don't you think that you should sanitize before using those values in a query? Feb 3, 2018 at 16:37

4 Answers 4

153

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.

6
  • What if you want to use operators such as $gt inside the query? Sep 29, 2016 at 14:03
  • You replace value by your query like { $gt: 50 }
    – maxdec
    Sep 29, 2016 at 14:15
  • How to pass regular express using above solution var query = {}; query[name] = value; ? Apr 28, 2017 at 9:05
  • 3
    I succeed var query = {}; query['registrationNo'] = { "$regex": sCode, "$options": "m" } ; Apr 28, 2017 at 15:53
  • 1
    @levelone someone was faster than me :)
    – maxdec
    Apr 2, 2018 at 20:57
74

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);
});
7
  • 1
    Your answer is much straight forward!
    – user523234
    Oct 26, 2016 at 13:05
  • 1
    This doesn't work as a direct mongo query; you get an error back E QUERY SyntaxError: Unexpected token [. I'm not sure how it can work in node.js? Nov 22, 2016 at 14:58
  • I think the reason is that nodejs will do transformation when it interact with mongodb.
    – KiwenLau
    Nov 23, 2016 at 1:53
  • this work on native mongodb drive for nodejs ! Thanks!
    – Guihgo
    Dec 1, 2016 at 0:24
  • Thank you! This worked in my much more abstract code for which the accepted answer made no sense (for the record, react not nodeJs). Dec 3, 2016 at 4:35
7

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.

5

use like this if the object is nested.

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.