Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

node.js - How to access error (thrown in post validate hook) when saving a document in mognoose?

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);
}
})```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...