kumarD
kumarD

Reputation: 594

Callback is not a function in mongoose.find({})

I am new to Node.js and mongoose, i am trying to query objects from a mongo collection using find({}) and the function is as follows :

schema.statics.listAllQuizes = function listAllQuizes(){
Model.find({},function(err,quizes,cb){
    if(err){
        return cb(err);
    }else if(!quizes){
        return cb();
    }
    else {
        return cb(err,quizes);
    }
});};

But when i call this function i get an error saying

        return cb(err,quizes);
               ^
        TypeError: cb is not a function

I am stuck at this point, can someone please help me with this, thanks in advance.

Upvotes: 3

Views: 10856

Answers (2)

robertklep
robertklep

Reputation: 203304

The callback should an argument to listAllQuizes, not an argument to the anonymous handler function.

In other words:

schema.statics.listAllQuizes = function listAllQuizes(cb) {
  Model.find({}, function(err, quizes) {
    if (err) {
      return cb(err);
    } else if (! quizes) {
      return cb();
    } else {
      return cb(err, quizes);
    }
  });
};

Which, logically, is almost the same as this:

schema.statics.listAllQuizes = function listAllQuizes(cb) {
  Model.find({}, cb);
};

Here's an example on how to use it:

var quiz = App.model('quiz');

function home(req, res) { 
  quiz.listAllQuizes(function(err, quizes) {
    if (err) return res.sendStatus(500);
    for (var i = 0; i < quizes.length; i++) {
      console.log(quizes[i].quizName)
    }
    res.render('quiz', { quizList : quizes });
  });
} 

Upvotes: 6

Wex
Wex

Reputation: 15695

Assuming you have code somewhere that looks like this:

foo.listAllQuizzes(function (err, quizzes) {
  ...
});

Then your function listAllQuizzes is passed a callback:

schema.statics.listAllQuizzes = function (cb) {
  Model.find({}, function(err, quizzes) {
    if (err) return cb(err);
    cb(null, quizzes);
  });
};

Upvotes: 3

Related Questions