猫鼬-'pre'中间件返回错误 [英] Mongoose - Return error in 'pre' middleware
本文介绍了猫鼬-'pre'中间件返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果在schema.pre('save')
中验证失败,如何发送自定义错误消息?例如,如果我具有聊天功能,可以在其中创建新对话,那么我想检查与给定参与者的对话是否已经存在,因此我可以这样做:
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();
}
});
});
推荐答案
在调用next
报告错误时传递Error
对象:
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();
}
});
});
文档此处.
这篇关于猫鼬-'pre'中间件返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文