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?
Set variable value in MongoDB save() methodUse db. yourCollectionName. save(yourVariableName) to set variable value, wherein “yourVariableName” is your variable.
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
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
.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With