gpt4 book ai didi

node.js - 尝试在 Restify API 中使用 Mongoose 保存模型时不会返回响应

转载 作者:可可西里 更新时间:2023-11-01 10:44:33 25 4
gpt4 key购买 nike

我正在使用 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();
}
},

最佳答案

此问题的一个原因可能是您有 pre save hook哪些错误是静默的。

如果您发现您的模型为 .pre('save' () => {...})函数,然后在调用 save 后仔细检查此方法是否已达到, 并且它返回时没有错误。

可以找到有关 mongoose 中间件的文档 here

关于node.js - 尝试在 Restify API 中使用 Mongoose 保存模型时不会返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12974230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com