Node.js mongodb回调问题

Node.js mongodb trouble with callbacks

本文关键字:问题 回调 mongodb js Node      更新时间:2023-09-26

因此,我试图创建一个注册路由,检查用户是否首先存在,并且我在一个单独的函数中有数据库调用,该函数需要在完成后返回truefalse。问题是我对回调不太熟悉,而且我搜索到的所有东西似乎都不起作用,却一直给我提供异步的东西

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

您需要使用如下回调:

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未定义的原因是您没有将第二个参数传递给pullUserFromDatabase(username)提供第二个自变量,例如pullUserFromDatabase(username, function(result) {/* do something here with the result variable */})

如果你对aync&回调,您可能会发现使用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
        }
    });
    ...

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

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

"didn't get far"return之后执行类似的步骤,这样回调就不会被多次调用。