如何解决我如何从猫鼬模式中获取特定的错误消息?
我正在尝试在Mongoose中设置用户验证,并努力使特定消息出现。这是我的模特
const userSchema = new Schema({
name: {
type: String,required: [true,"Name required"]
},email: {
type: String,"Email required"]
},password: {
type: String,"Password required"],minlength: [6,"Password must be at least six characters"]
},date: { type: Date,default: Date.now },albums: [{ type: Schema.Types.ObjectId,ref: "Album"}]
})
我目前有这种方法可以创建一个新用户。我相信我将需要找到一种更好的方法来查看电子邮件是否存在(可能存在于模型中),但是现在这就是我所拥有的。
registerUser(req,res) {
const { name,email,password } = req.body
db.User.findOne({ email: email })
.then(exists => {
if (exists) res.redirect("/register")
else {
db.User.create({ name,password })
.then((err,res) => {
if (err) console.log(err.errors.password.message)
})
}
})
},
我输入的密码长度无效以尝试获取消息,但出现大错误:
(node:49238) UnhandledPromiseRejectionWarning: ValidationError: User validation failed: password: Password must be at least six characters
[0] at model.Document.invalidate (/Users/user/Desktop/untitled folder/portfolio-projects/project/node_modules/mongoose/lib/document.js:2579:32)
[0] at /Users/user/Desktop/untitled folder/portfolio-projects/project/node_modules/mongoose/lib/document.js:2399:17
[0] at /Users/user/Desktop/untitled folder/portfolio-projects/project/node_modules/mongoose/lib/schematype.js:1220:9
[0] at processTicksAndRejections (internal/process/task_queues.js:79:11)
[0] (node:49238) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
[0] (node:49238) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
为了只收到错误消息,我需要更改什么?
解决方法
过去我对此有疑问,这帮助我解决了问题
if(err) {
if (err.name === 'ValidationError') {
console.error(Object.values(err.errors).map(val => val.message))
}
}
这将返回Password must be at least six characters
更新-
首先,您需要在将promises
与callbacks
混合使用时修复代码,就像在使用.then
语法一样,这里没有(err,res)
对象>
更清洁的方法是
registerUser(req,res) {
const { name,email,password } = req.body
db.User.findOne(email)
.then(exists => {
if (exists) res.redirect("/register")
else {
db.User.create({ name,password })
.then(res => {
console.log(res);
}).catch(err => {
if (err.name === 'ValidationError') {
console.error(Object.values(err.errors).map(val => val.message))
}
})
}
}).catch(err => console.error(err))
};
您可以像这样使用Async/Await
进一步清理
async registerUser(req,password } = req.body
try{
const userExist = await db.User.findOne(email);
if(userExist){
res.redirect("/register")
}
else{
const createdUser= await db.User.create({ name,password })
res.redirect('')
}
}
catch(err){
if (err.name === 'ValidationError') {
console.error(Object.values(err.errors).map(val => val.message))
}
else{
console.error(err);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。