This is the mongoose schema. I have added a post validation hook to it and I throw an error in it. I want to access the error message when I save the document for this schema in mongoose.
const profileSchema = new mongoose.Schema({
shop : {
type : String
required : [true , "Team is required"]
},
name: {
type: String,
required: [true , "Name is required"],
minLength: [5, "Name should atleast be 5 characters"],
validate: {
validator: (name: string) => name.trim().length >= 5,
message: "Name should atleast be 5 characters"
}
}
}
profileSchema.post("validate", async doc => {
const allProfiles = await profileModel.find({team : doc.team})
for (const profile of allProfiles) {
if (profile.name === doc.name) {
throw new Error("Name already exists")
}
}
})
export const profileModel = mongoose.model("Profile", profileSchema);
I want to access the "Name already exists" error when I call the save method.
newProfile.save((err,doc) => {
if(err){
// should I do this
console.log(err.name.message);
}
})```
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…