在我的 Node.js Express 应用程序中,我只是设置用户登录,这是我第一次进行这种自学。
我这里有这个功能
var db = require('mongojs').connect('localhost/busapp', ['users']),
crypto = require('crypto');
exports.new = function(req, res) {
function User(email, password) {
this.email = email;
this.password = password;
}
var user = new User(req.body.user.email, req.body.user.password);
console.log(user.email + user.password);
db.users.find({'email':user.email}, function(err, userFound) {
if (err) {
console.log('We have an error :(');
} else if (userFound === 'undefined') {
console.log('We couldn\'t find the user ' + user.email);
return;
} else {
console.log('We have fixed the error, hooorraayyy!! ' + userFound[0].email)
}
});
}
但是控制台日志显示为
We found the user! undefined
我不确定我做错了什么,如果有人能阐明这种情况,那就太好了,谢谢!
好吧,我通过将代码更改为上面的代码来修复它,但现在我遇到了一个问题,如果我尝试搜索不存在的电子邮件,它会导致我的整个应用程序崩溃并出现以下错误:
C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\connection\server.js:529
throw err;
^
TypeError: Cannot read property 'email' of undefined
at C:\Users\Gacnt\Desktop\Busapp\routes\session.js:22:72
at C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\cursor.js:159:16
at commandHandler (C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\cursor.js:628
:16)
at null.<anonymous> (C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\db.js:1709:
18)
at g (events.js:175:14)
at EventEmitter.emit (events.js:106:17)
at Server.Base._callHandler (C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\con
nection\base.js:130:25)
at C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\connection\server.js:522:20
at MongoReply.parseBody (C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\respons
es\mongo_reply.js:132:5)
at null.<anonymous> (C:\Users\Gacnt\Desktop\Busapp\node_modules\mongojs\node_modules\mongodb\lib\mongodb\connection\
server.js:481:22)
PS C:\Users\Gacnt\Desktop\Busapp>
最佳答案
我从未使用过 mongo 的 javascript 驱动程序,但看起来您的查询行本身是错误的。对于我来说,您的用户对象是 undefined ,它没有电子邮件属性。 Mongo js 驱动程序甚至在实际将查询传递给 mongo 引擎之前就尝试解析此属性的值,这对于非现有用户会失败,因此会出现异常。尝试在查询mongo之前添加检查用户对象是否正确。
顺便说一句,从您的代码片段来看,不清楚您在哪里打印消息“我们找到了一个用户!”未定义'请仔细检查这一点 希望这有帮助
关于javascript - 在 MongoDB 中,为什么搜索不存在的电子邮件会使我的整个应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15847290/