Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
    });
});
like image 785
Alex Wohlbruck Avatar asked Dec 20 '16 13:12

Alex Wohlbruck


2 Answers

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.

like image 91
JohnnyHK Avatar answered Oct 12 '22 12:10

JohnnyHK


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();
    });
});
like image 28
virgiliogm Avatar answered Oct 12 '22 11:10

virgiliogm