Ale*_*uck 6 mongoose node.js express
如果验证失败,如何发送自定义错误消息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();
}
});
});
Run Code Online (Sandbox Code Playgroud)
Error在调用时传递对象next以报告错误:
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();
}
});
});
Run Code Online (Sandbox Code Playgroud)
文档在这里.
| 归档时间: |
|
| 查看次数: |
3381 次 |
| 最近记录: |