【问题标题】:How can i get specific error messages from a Mongoose Schema?如何从 Mongoose Schema 中获取特定的错误消息?
【发布时间】:2020-12-03 17:03:56
【问题描述】:

我正在尝试在 Mongoose 中设置用户验证,并努力让特定消息出现。这是我的模型

const userSchema = new Schema({
    name: { 
        type: String, 
        required: [true, "Name required"]
    },
    email: { 
        type: String, 
        required: [true, "Email required"] 
    },
    password: { 
        type: String, 
        required: [true, "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, email, 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. 

为了只收到错误消息,我需要进行哪些更改?

【问题讨论】:

    标签: node.js mongodb express validation mongoose


    【解决方案1】:

    我过去在这方面遇到过问题,这帮助我解决了问题

     if(err) {
        if (err.name === 'ValidationError') {
          console.error(Object.values(err.errors).map(val => val.message))
        }
      }
    

    这将返回Password must be at least six characters

    更新-

    首先,您需要修复您的代码,因为您将 promisescallbacks 混合在一起,就好像您使用的是 .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, email, 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, res) {
        const { name, email, password } = req.body
        try{
          const userExist = await db.User.findOne(email);
          if(userExist){
            res.redirect("/register")
          }
          else{
            const createdUser= await db.User.create({ name, email, password })
            res.redirect('')
          }
        }
        catch(err){
          if (err.name === 'ValidationError') {
            console.error(Object.values(err.errors).map(val => val.message))
          }
          else{
            console.error(err);
          }
        }
    

    【讨论】:

    • 我试过了,但仍然收到同样的错误信息。
    • 好的,现在添加了
    • 这行得通。谢谢!我最初将它设置为异步方法。我会尝试使用您发布的内容将其转换回来。
    • Async 方法更简洁易读!但是是的,两种方式都有效
    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2021-06-03
    • 1970-01-01
    • 2021-01-29
    • 2023-03-24
    • 2012-07-08
    • 2019-10-28
    • 2020-08-04
    相关资源
    最近更新 更多