我正在用 express 编写后端 javascript,但由于某种原因,我的函数在调用时未定义。它看起来像这样:
//快递路线如下所示:
exports.check = function(req, res) { //check if username is in database
var my_result = authenticator(req); //authenticator is defined below
console.log(typeof(authenticator(req))); //returns undefined
};
function authenticator(req) {
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'users');
db.once('open', function callback() {
var personschema = mongoose.Schema({
username: String,
password: String
})
var person1 = db.model('personcollection', personschema)
person1.find({
username: req.body.username,
password: req.body.password
}, function(err, obj) {
if (obj.length === 0) {
return "yay";
} else {
return "neigh";
}
} //end function
当我把它放在 express 路由中时,该函数本身就可以工作,但我想用尽可能少的代码保持路由的美观。这是一个选择吗?
谢谢你的帮助。