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

标签 node.js express mongoose

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

相关文章:

node.js - Twilio - 检测用户何时开始说话

javascript - 类型 'authorization' 上不存在属性 'Request'

node.js - 如何避免多个 Mongoose 操作的嵌套 promise ?

node.js - 在 mongoose 中使用 mongodb 多键索引方法索引引用数组

node.js - Nodejs | Mongoose - 根据多个不同字段查找文档

node.js - 不使用 Visual Studio 安装 bcrypt

mysql - 从时间戳获取本地时间

javascript - 如何处理 Electron 中的本地文件上传?

node.js - 如何在 Express 中出现未捕获错误后呈现 500 响应?

javascript - 如何在快速验证器中验证文件输入?