【发布时间】:2020-07-30 09:59:08
【问题描述】:
在使用邮递员测试我的 api 时,我在使用 mongoose 时遇到了 1 个问题。
-
userSchema中的throw new Error()都不会返回route.postcatch 错误。
如何让throw new Error() 返回到router.post 脚本?
当电子邮件和密码与数据库中的内容匹配时,脚本可以正常工作。
如果我console.log(no email) 或no password 使用透视if() 语句,它们会触发,但throw new Error() 消息不会传递到router.post 上的catch 语句。如果我在 router.post 上 console.log(error) 我得到
错误:未找到电子邮件 在 Function.userSchema.statics.validatePassword (C:\Users\Samson\Documents\JS\nodeProjects\task-manager\src\models\users.js:60:15) 在 processTicksAndRejections (internal/process/task_queues.js:97:5) 在异步 C:\Users\Samson\Documents\JS\nodeProjects\task-manager\src\routers\user.js:66:22
但是传回邮递员的是{}
下面我将提供用户模型、模式和路由的代码和屏幕截图。post
Schema Object
userSchema.statics.validatePassword = async function (email, password) {
const user = this;
const userObj = await user.findOne({
"email": email
});
if (!userObj) {
console.log("no email")
throw new Error("No email found ");
}
const answer = await bcrypt.compare(password, userObj.password);
if (!answer) {
console.log("no password")
throw new Error('Incorrect Password');
}
return answer;
}
猫鼬用户模型
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(name) {
if (name.length <= 0) {
throw new Error("Please fill in a name");
}
}
},
age: {
type: Number,
required: true,
validate(age) {
if (age < 18) {
throw new Error('Participates must be 18 years of age or older');
}
}
},
email: {
type: String,
required: true,
lowercase: true,
trim: true,
unique: true,
validate(address) {
if (!validator.isEmail(address)) {
throw new Error('Please enter a valid email address');
}
}
},
password: {
type: String,
required: true,
trim: true,
validate(secret) {
if (secret.length <= 6 || secret.includes('password')) {
throw new Error("Please select a password longer than 6 characters and that doesn't include the term password");
}
}
}
});
router.post
router.post('/users/login', async (req, res) => {
try {
const user = await User.validatePassword(req.body.email, req.body.password);
res.status(200).send("user and password validated " + user);
} catch (error) {
console.log(error)
res.status(400).send(error);
}
});
【问题讨论】:
标签: javascript node.js express mongoose mongoose-schema