如果我在 schema.pre('save')
中验证失败,如何发送自定义错误消息?例如,如果我有一个聊天功能,您可以在其中创建一个新对话,我想检查与给定参与者的对话是否已经存在,所以我可以这样做:
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
对象:
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();
}
});
});
文档 here .
关于node.js - Mongoose - 在 'pre' 中间件中返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243575/