0

Hi I am using Express to work with MongoDB. I am pretty new to both. I got a find function working, it looks like this:

function find (current_collection, cb) {
  getCollection(current_collection, function (err, collection) {
    collection.findOne({
      'identity.sender.id': '1234abcd'
    }, function (err, result) {
      // ... some err and cb handling
    });
  });
}

I logged the result and everything looks fine. I want to this code somewhere else, so I tried to use variables in the query and turned the function into something like this:

function find (current_collection, val, cb) {
  getCollection(current_collection, function (err, collection) {
    collection.findOne({
      'identity.sender.id': val
    }, function (err, result) {
      // ... some err and cb handling
    });
  });
}

// I then called the function on a separate file like this, and it worked

getModel().findSender('users', '1218186478216025', function(err, result){
       res.render('user_model_test', { 
           sender_id: result.identity.sender.id
       });
   });

Data displayed totally fine on the webpage. However, when I tried to go one step further but using variable for the query attribute, everything stopped working and i got error:

function find (current_collection, field, val, cb) {
  getCollection(current_collection, function (err, collection) {
    collection.findOne({
      field : val
    }, function (err, result) {
      // ... some err and cb handling
    });
  });
}

// I then called the function on a separate file, this time, did not work:

   getModel().findSender('users', 'identity.sender.id', '1218186478216025', function(err, result){
       res.render('user_model_test', { 
           sender_id: result.identity.sender.id
       });
   });

Not sure what I have done incorrectly. I think is something to do with the data format of the query field - the 'identity.sender.id' part. but i can't figure out. Please help!! Thanks in advance!

gdzla
  • 1
  • 3
  • `find`. doesn't return anything and it's asynchronous. – Mike Cluck Aug 24 '16 at 20:34
  • thanks @MikeC i didnt have a problem with the return part, it was working ... until I turned the query field into a variable. – gdzla Aug 24 '16 at 20:43
  • 1
    But look at your `find` function. It doesn't return anything. `x` will always be `undefined`. – Mike Cluck Aug 24 '16 at 20:44
  • Hi @MikeC thanks for flagging up the asynchronous issue, i have fixed that and have clarified the problem, hope that will make more sense. thx – gdzla Aug 24 '16 at 22:21
  • 1
    That's because you are making a property *literally* called "field." Not your variable value. You'll need to do something like `var query = {}; query[field] = val; collection.findOne(query, ...` – Mike Cluck Aug 24 '16 at 22:24
  • problem solved! thanks a lot! – gdzla Aug 24 '16 at 22:34

0 Answers0