简体   繁体   中英

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,

  • mapper == collections returned from db
  • key == dynamic key (in this case it is customerInfo )

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM