-2

Function that holds mongoose query

module.exports.getSiteState = function(callback){
    var data;
    Count.find(function(err,result){
        if (err) {
            return callback(err);
        }else{
            data = result[0].count;
            callback(err,data); 
        }
    });
}

function that calls model, and when I use return instead of callback it return before query.

var Data = require('../models/users');
router.get('/adminIndex', function(req,res){
  //console.log(User.getSiteState());
  var count = User.getSiteState();
  console.log("1  "+count);
  res.render('admin/adminIndex',{layout: 'adminLayout'});
})
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • events.js:160 throw er; // Unhandled 'error' event ^ TypeError: callback is not a function at /Users/jay/Desktop/nodeProjects/SmartCity/models/users.js:88:4 at Query. (/Users/jay/Desktop/nodeProjects/SmartCity/node_modules/mongoose/lib/model.js:3419:16) at /Users/jay/Desktop/nodeProjects/SmartCity/node_modules/kareem/index.js:264:21 at /Users/jay/Desktop/nodeProjects/SmartCity/node_modules/kareem/index.js:127:16 at _combinedTickCallback (internal/process/next_tick.js:67:7) at process._tickCallback (internal/process/next_tick.js:98:9) – jay kakadiya Feb 19 '17 at 05:21
  • That's because when you call `getSiteState()` you don't pass a callback function. Also, please [edit] your question to show the error details there directly and then delete your comment. – nnnnnn Feb 19 '17 at 05:22
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Frxstrem Feb 19 '17 at 05:22
  • where is your callback function ? @jaykakadiya – Divyesh Kanzariya Feb 19 '17 at 05:35

1 Answers1

1

The getSiteState function doesn't return a value. It is asynchronous and expects that you pass a callback function as parameter. This callback can then be used to get the results:

var Data = require('../models/users');
router.get('/adminIndex', function(req,res) {
    User.getSiteState(function(err, count) {
        console.log("1  "+count);
        res.render('admin/adminIndex',{layout: 'adminLayout'});
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928