【发布时间】:2012-10-10 01:36:21
【问题描述】:
我正在使用 Restify 和 Mongoose 为 NodeJS 构建一个 API。在找到用户并验证其密码后的以下方法中,我试图在将响应发送回用户之前保存一些登录信息。问题是响应永远不会返回。如果我将响应放在保存调用之后和外部,则数据永远不会持久保存到 MongoDB。难道我做错了什么?并且帮助会很棒,因为我在过去 2 天里一直在做这件事。
login: function(req, res, next) {
// Get the needed parameters
var email = req.params.email;
var password = req.params.password;
// If the params contain an email and password
if (email && password) {
// Find the user
findUserByEmail(email, function(err, user) {
if (err) {
res.send(new restify.InternalError());
return next();
}
// If we found a user
if (user) {
// Verify the password
user.verifyPassword(password, function(err, isMatch) {
if (err) {
res.send(new restify.InternalError());
return next();
}
// If it is a match
if (isMatch) {
// Update the login info for the user
user.loginCount++;
user.lastLoginAt = user.currentLoginAt;
user.currentLoginAt = moment.utc();
user.lastLoginIP = user.currentLoginIP;
user.currentLoginIP = req.connection.remoteAddress;
user.save(function (err) {
if (err) {
res.send(new restify.InternalError());
return next();
}
// NEVER RETURNS!!!!
// Send back the user
res.send(200, user);
return next();
});
}
else {
res.send(new restify.InvalidCredentialsError("Email and/or password are incorrect."));
return next();
}
});
}
else {
res.send(new restify.InvalidCredentialsError("Email and/or password are incorrect."));
return next();
}
});
}
else {
res.send(new restify.MissingParameterError());
return next();
}
},
【问题讨论】:
-
当你调用
user.save但没有得到回调时,用户数据会被持久化吗?如果没有,这听起来像是数据库上的写锁可能被另一个连接持有。 -
在使用这种方法时,我只有一个使用 mongoose 创建的连接。调用 user.save 时,用户数据不会持久化到 MongoDB。
-
与数据库的连接是否打开? mongoose 缓冲命令直到第一个连接打开。
-
这可能是因为我已经去数据库通过他们的电子邮件找到了一个用户。我还没有完成这项工作,所以如果有人能展示或解释如何做到这一点,我将不胜感激。可以打开另一个数据库连接使用吗??
-
我也遇到了同样的问题。您找到解决方案了吗?
标签: node.js mongodb mongoose restify