Alex Wohlbruck
Alex Wohlbruck

Reputation: 1436

Mongoose - Return error in 'pre' middleware

How can I send a custom error message if my validation fails in schema.pre('save')? For example, if I have a chat feature, where you create a new conversation, I want to check if a conversation with the given participants already exists, so I can do:

ConversationSchema.pre('save', function(next, done) {
    var that = this;
    this.constructor.findOne({participants: this.participants}).then(function(conversation) {
        if (conversation) {
            // Send error back with the conversation object
        } else {
            next();
        }
    });
});

Upvotes: 11

Views: 7100

Answers (2)

virgiliogm
virgiliogm

Reputation: 976

I agree with JohnnyHK's answer except that it doesn't seem possible to add custom properties to the Error object. When receiving the error and trying to access that property the value is undefined so the solution is that you can send a custom error message but not add custom properties. My code would be something like:

ConversationSchema.pre('save', function(next) {
    this.constructor.findOne({participants: this.participants}, function(err, conversation) {
        if (err) next(new Error('Internal error'));
        else if (conversation) next(new Error('Conversation exists'));
        else next();
    });
});

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311965

Pass an Error object when calling next to report the error:

ConversationSchema.pre('save', function(next, done) {
    var that = this;
    this.constructor.findOne({participants: this.participants}).then(function(conversation) {
        if (conversation) {
            var err = new Error('Conversation exists');
            // Add conversation as a custom property
            err.conversation = conversation;
            next(err);
        } else {
            next();
        }
    });
});

Docs here.

Upvotes: 14

Related Questions