gpt4 book ai didi

node.js - Mongoose - 在 'pre' 中间件中返回错误

转载 作者:搜寻专家 更新时间:2023-10-31 22:30:50 25 4
gpt4 key购买 nike

如果我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com