Custom Error Messages with Mongoose

前端 未结 8 479
旧巷少年郎
旧巷少年郎 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");
      }
    });
    

提交回复
热议问题