Jithesh Gopinathan Jithesh Gopinathan - 5 months ago 13
jQuery Question

My callback function not working

I am do a nodeJS application, in which there is a call back function to persist the value to the database(MongoBD). The callback function as below:

exports.add = function(student, cb) {
var collection = db.get().collection('students');
collection.insert(student, function(err) {
if (err) {
throw err;
}
console.log("Record added");
});
}


The above call back function is called from the another fuction as below:

router.post("/add", function(req,res){
var student = req.body;
Students.add(student, function(err) {
if (err) {
throw err;
}
var respOut = JSON.stringify({id:student.id});
console.log("respOut");
res.send(respOut);
});
});


The call back function is called from the above bolded(Students.add) section. Currently I am able to persist the data on to the DB. But not getting any output on the console( given console out as ->
console.log("respOut");
or any response in the UI(from above code). Is there any problem with my call back function? or I am missing anything?

Answer

You're not using cb in your Students.add method.

The easiest would be to just pass the callback through to collection.insert:

exports.add = function(student, cb) {
    var collection = db.get().collection('students');
    collection.insert(student, cb);
}
Comments