Boy
Boy

Reputation: 612

Express js use values from mongodb to outside of the query

I am new with express js and node js. I am wonder if its possible to do this or not.

1st thing I'm trying to get the count on 1 query.

2nd I query collection login. loop it and format and get the name values using ids.

I get undefined on count1 and I see it ommitted on the json response.

how do I pass the query returns outside of the query?

router.post('/logmein', function(req, res, next) {
    var email = req.param('email');
    var password = req.param('password');
    var count1;

    MongoClient.connect(MongoUrl, function(err, db) {
        if (err) return;

        db.collection('users').count({email: email,password: md5(password)}, function(err, count) {
            count1 = count;
        });

        db.collection('login').find({email: email,password: md5(password)}).toArray(function(err, results){
            console.log(results); // output all records
        });


        //use results
        /*
        foreach each results format with other info

        var new_array;
        */
        res.json({"success": true,"count":count1,new_array: new_array});
    }); 
});

Upvotes: 2

Views: 726

Answers (2)

Stavros Zavrakas
Stavros Zavrakas

Reputation: 3053

Async issues, you have to look more at it. Use the async module and then you will be able to fire the queries in parallel. Finally, you will have the results in the final callback. This snippet will fix your issue:

var async = require('async');

router.post('/logmein', function (req, res, next) {
  var email = req.param('email');
  var password = req.param('password');
  var retResults;
  var count1;

  MongoClient.connect(MongoUrl, function (err, db) {
    if (err) return;

    async.parallel([
      function(callback){ 
        db.collection('users').count({ email: email, password: md5(password) }, function (err, count) {
          return callback(err, count);
        });
      },
      function(callback){
        db.collection('login').find({ email: email, password: md5(password) }).toArray(function (err, results) {
          return callback(err, results);
        });
      }
    ], function(err, results) {
      if (err) {
        // @todo: handle the error
      }

      count1 = results[0];
      retResults = results[1];


      //use results
      /*
      foreach each results format with other info

      var new_array;
      */
      res.json({ "success": true, "count": count1, new_array: new_array });

    };
  });
});

Upvotes: 1

Alexey B.
Alexey B.

Reputation: 12033

You need something like async.parallel to control the async flow of your nodejs application

async.parallel([
    function(callback){ ... },
    function(callback){ ... }
], function(err, results) {
    // optional callback
};

Upvotes: 1

Related Questions