我的回调功能不起作用

时间:2016-06-19 05:10:06

标签: javascript jquery angularjs node.js

我正在做一个nodeJS应用程序,其中有一个回调函数来将值保存到数据库( MongoDB )。回调函数如下:

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

上面的回调函数是从另一个函数调用的,如下所示:

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);
    });
});

从上面的粗体(Students.add)部分调用回调函数。目前我能够将数据保存到数据库中。但是没有在控制台上获得任何输出(给出控制台作为 - &gt; console.log("respOut");或UI中的任何响应(来自上面的代码)。我的回调功能有问题吗?或者我遗漏了什么?< / p>

1 个答案:

答案 0 :(得分:0)

您未在cb方法中使用Students.add

最简单的方法是将回调传递给collection.insert

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