1024programmer Java Return error in “before” middleware. -Mongoose-Returnerrorin’pre’middleware

Return error in “before” middleware. -Mongoose-Returnerrorin’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:

How do I send a custom error message if my validation fails in schema.pre(‘save’)? For example, if I have a chat function, when When you create a new conversation, I want to check if a conversation with a given participant already exists, so I can:

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

1 solution

#1


3

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

When calling next to report an error, pass an error object:

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.

Documentation.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/754399

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索