Pradeep Simha
Pradeep Simha

Reputation: 18123

Mongodb Node.js finding value by a dynamic key

I am trying to find a value of a key from a mongodb, but not able to succeed till now. Here is my sample output:

{ "_id" : { "$oid" : "52cfc91adbffcbe08ccf94b0"} , "customerInfo" : "value"}

say if I give "customerInfo" I should be able to get "value". Note that customerInfo is dynamic key, which will be passed by the user, so I am out of luck to hard code the values in the code. I tried with below code,

db.urlmapper.find({urlmapper: key}, function(err, users) {
      users.forEach( function(val) {
        console.log("found data: " + JSON.stringify(val));
      } );
    });

where,

It doesn't return any data. Can someone kindly help me how to achieve this? Since I am very beginner to MongoDB.

Upvotes: 1

Views: 789

Answers (1)

Brett
Brett

Reputation: 3885

The code that you have is setting a key called urlmapper on the object. Instead you need to use the value of the variable urlmapper. Something like this:

var query = {};
query[urlmapper] = key;

db.urlmapper.find(query, function(err, users) {
  users.forEach(function(val) {
    console.log("found data: " + JSON.stringify(val));
  });
});

Upvotes: 1

Related Questions