【问题标题】:Mongoose - Return error in 'pre' middlewareMongoose - 'pre' 中间件中的返回错误
【发布时间】:2017-05-05 17:50:40
【问题描述】:

如果我在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();
        }
    });
});

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    调用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.

    【讨论】:

      【解决方案2】:

      我同意 JohnnyHK 的回答,但似乎无法将自定义属性添加到 Error 对象。收到错误并尝试访问该属性时,该值未定义,因此解决方案是您可以发送自定义错误消息但不添加自定义属性。我的代码是这样的:

      ConversationSchema.pre('save', function(next) {
          this.constructor.findOne({participants: this.participants}, function(err, conversation) {
              if (err) next(new Error('Internal error'));
              else if (conversation) next(new Error('Conversation exists'));
              else next();
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-16
        • 2022-01-13
        • 2016-04-13
        • 1970-01-01
        相关资源
        最近更新 更多