Custom Error Messages with Mongoose

前端 未结 8 482
旧巷少年郎
旧巷少年郎 2021-02-01 04:06

So according to the mongoose docs, you are supposed to be able to set a custom error message in the schema like so:

 var breakfastSchema = new Schema({
  eggs: {         


        
相关标签:
8条回答
  • 2021-02-01 05:00

    Thanks for all answers, I've figured out my problem.

    My schema is like that.

    var User = new Schema({
      username: {type: String, required: [true, "Username is required"], unique: true},
      email: {type: String, required: [true, "Email is required"], unique: true},
      password: {type: String, required: true, unique: false},
    });
    

    I recommend to use like a function.

    You can use like this;

    User.post("save", function (error, doc, next) {
    
      if (error.keyValue.email != null && error.name === "MongoError" && error.code === 11000) {
    
        console.log("Email must be unique");
      } else if (error.keyValue.username != null && error.name === "MongoError" && error.code === 11000) {
        console.log("Username must be unique");
      } else {
        console.log("not found any idea, search for another reasons");
      }
    });
    
    0 讨论(0)
  • 2021-02-01 05:05

    you can add a custom async validator. for example:

     {
          validator: (value) => {
            return UserModel.findOne({ email: value })
              .then(user => Promise.resolve(user == null))
              .catch(error => Promise.reject(false));
          },
          message: "User with this email already exists"
     }
    
    
    0 讨论(0)
提交回复
热议问题