Node.js mongodb与callback的麻烦

所以我试图创build一个注册路线,检查用户是否先存在,我有一个单独的函数中的数据库调用,当它完成时需要返回truefalse 。 问题是我不是很熟悉callback和整个asynchronous的东西,我已经search了一切似乎并没有工作不断给我。

TypeError: callback is not a function

这是我的代码任何帮助或方向将不胜感激。

 function pullUserFromDatabase(username, callback) { console.log(username); //for debug mongodb.connect(url, function(err, db) { if(err) { console.log("didn't get far" + err) //for debug } var collection = db.collection(username); collection.findOne({username}, function(err, item) { if(err) { console.log("nope it broke" + err) //for debug } else { console.log("it worked" + JSON.stringify(item)) //for debug callback(true); } }); }); } app.post("/signup", function(req, res) { var username = req.headers["username"], password = req.headers["password"], randomSalt = crypto.randomBytes(32).toString("hex"), passwordHashOutput = crypto.createHash('sha256').update(password + randomSalt).digest("hex"); if(!username || !password) { res.send("Username or password not provided.") } else if(pullUserFromDatabase(username)) { res.send("User exist.") } }); 

您需要使用callback如下:

 function pullUserFromDatabase(data, callback) { console.log(data.username); //for debug mongodb.connect(url, function(err, db) { if(err) { console.log("didn't get far" + err) //for debug } var collection = db.collection(data.collection); collection.find({"username": data.username}).count(function (err, count) { callback(err, !! count); }); }); }; app.post("/signup", function(req, res) { var username = req.headers["username"], password = req.headers["password"], randomSalt = crypto.randomBytes(32).toString("hex"), passwordHashOutput = crypto.createHash('sha256').update(password + randomSalt).digest("hex"); if(!username || !password) { res.send("Username or password not provided.") } var data = { username: username, collection: "collectionName" } if(!username || !password) { res.send("Username or password not provided.") } pullUserFromDatabase(data, function(err, exists) { if (err) { res.send(400, "Error - " + err); } else if(exists) { res.send(200, "User exists."); } res.send(200, "User does not exist."); }); }); 

callback未定义的原因是因为您没有将第二个parameter passing给pullUserFromDatabase(username)提供第二个参数,例如。 pullUserFromDatabase(username, function(result) {/* do something here with the result variable */})

如果你不太熟悉asynchronous和callback,你可能会发现使用promise更直观,但是它有自己的学习曲线。

在原始代码的情况下,这看起来像:

  ... if(!username || !password) { res.send("Username or password not provided."); return; } pullUserFromDatabase(username, function(result) { if(result) { res.send("User exist."); } else { // TODO: Handle this case. If res.send() is never called, the HTTP request won't complete } }); ... 

另外,您需要确保始终调用callback。 添加callback(false):

  console.log("nope it broke" + err); //for debug callback(false); 

"didn't get far"后执行类似的步骤,然后return因此callback不会被多次调用。