1

I am trying to create a method that will fetch a record from a collection based on a parameter and a value something like.

where parm is for instance the _id field in this schema.

getRecord('_id', '1234567876543')

getRecord(parm, value){
    db.collection.findOne( { parm : value } , function(err, item) {
        if (err) {
            console.error(err);
        }else if (item === null ) {
            console.error('record does not exist');
        }else {
            Record = JSON.stringify(item); 
        }
    });
}

What is happening is that this code is trying to fetch the colum parm from the table which does not exist, returning record does not exist every time.

How can I pass the value of the param in the findOne Query?

1 Answers1

5

If you wish to pass a variable in the key part of an object, you can pass it by using square brackets. In your case, do it like:

db.collection.findOne( { [parm] : value } , function(err, item) {

Or maybe, you could just assign it to an object like:

var query = {};
query[parm] = value;
db.collection.findOne( query , function(err, item) {...})
Parijat Purohit
  • 921
  • 6
  • 16