在express中调用函数 – undefined

我正在写后端JavaScript的快递,但由于某种原因,我的function是调用时未定义。 它看起来像这样:

// express route看起来像这样:

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 

当我把它放在快速路线里面的时候,这个function本身就起作用了,但是我想用尽可能less的代码保持路线漂亮。 这是一个select吗?

谢谢你的帮助。

欢迎来到JavaScript的奇妙的asynchronous世界:)
还有,Node.js世界。

发生这种情况是因为Node中没有networking可以同步完成 – 这意味着您必须使用callback。

您的authenticatorfunction应该看起来像这样:

 function authenticator(req, callback) { var mongoose = require('mongoose'); var db = mongoose.createConnection('localhost','users'); db.once('open', function() { 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) { // in this callback you do what you want with this result! callback(obj.length === 0); }); }); } 

两面说明:

  • 怎么保持数据库连接分开? 这样你会打开它的每个请求。
  • 您似乎将简单密码存储在数据库中,因为您将它们与请求中传递的内容进行比较:o您应该在数据库中真正encryption它们!

您正尝试从asynchronous函数中返回一个值。 句号 您对node.js和asynchronous编程有一个基本的误解,您需要阅读教程并围绕asynchronous代码进行打包,以及为什么它们不能返回值,并且必须使用callback(或事件或promise)。

http://nodejsreactions.tumblr.com/post/56341420064/when-i-see-some-code-that-returns-a-value-from-an-async