Mongoose: 从 post findOneAndUpdate 中间件返回 ValidationError 不包含消息

创建于 2018-02-25  ·  3评论  ·  资料来源: Automattic/mongoose

@vkarpov15此评论中建议了以下代码

schema.post('findOneAndUpdate', (result, next) =>{
  if (result.docField == 'invalidValue'){
    return next(new mongoose.Error.ValidationError('docField had an invalid value'));
  }
  // ...
});

但是ValidationError不包含自定义消息

docField 的值无效

相反,消息只是罐装消息

验证失败

这是来自以下字符串的 ValidationError:

{
    "errors": {},
    "_message": "Validation failed",
    "message": "Validation failed",
    "name": "ValidationError"
}

我在 v 4.13.8和 v 5.0.7中对其进行了测试

最有用的评论

@jeremyml你是对的,我的例子不正确

schema.post('findOneAndUpdate', (result, next) =>{
  if (result.docField == 'invalidValue'){
    var validationError = new mongoose.Error.ValidationError(null);
    validationError.addError('docField', new mongoose.Error.ValidatorError({ message: 'Invalid' })); 
    return next(validationError);
  }
  // ...
});

ValidationError 是路径到 ValidatorError 实例的映射,因此您需要添加其中一个

所有3条评论

嗨@jeremyml。 据我所知, @vkarpov15 似乎只是在帮助处理您建议的钩子的异步部分。 在查看了 ValidationError 的来源之后,如果你给它一个字符串而不是一个模型的实例,你的消息似乎只会是“验证失败”

function ValidationError(instance) {
  this.errors = {};
  this._message = '';
  if (instance && instance.constructor.name === 'model') {
    this._message = instance.constructor.modelName + ' validation failed';
    MongooseError.call(this, this._message);
  } else {
    this._message = 'Validation failed';
    MongooseError.call(this, this._message);
  }
  this.name = 'ValidationError';
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this);
  } else {
    this.stack = new Error().stack;
  }
  if (instance) {
    instance.errors = this.errors;
  }
}

如果您可以忍受 Error 的实例,则以下工作:

#!/usr/bin/env node
'use strict'

const mongoose = require('../lib/test_db')
const Schema = mongoose.Schema

const testSchema = Schema({
  docField: String
})

testSchema.post('findOneAndUpdate', (result, next) => {
  let err = new Error('invalid docfield value')
  err.name = 'ValidationError'

  if (result.docField === 'invalidValue') {
    return next(err)
  }
})

const Test = mongoose.model('test', testSchema)

const test = new Test({
  docField: 'valid'
})

let savedDoc = test.save()
savedDoc.then(() => {
  Test.findOneAndUpdate({
    _id: test.id
  }, { docField: 'invalidValue' }, { runValidators: true, new: true }, (err, res) => {
    if (err) { return console.error(err) }
    console.log(res)
  })
})

输出:

InspiredMacPro:Help lineus$ ./mongoose5/6171/index.js 
{ ValidationError: invalid docfield value
    at Query.testSchema.post (/Users/lineus/dev/Help/mongoose5/6171/index.js:12:25)
    at callMiddlewareFunction (/Users/lineus/dev/Help/mongoose5/node_modules/kareem/index.js:399:23)
    at next (/Users/lineus/dev/Help/mongoose5/node_modules/kareem/index.js:193:9)
    at Kareem.execPost (/Users/lineus/dev/Help/mongoose5/node_modules/kareem/index.js:217:3)
    at _cb (/Users/lineus/dev/Help/mongoose5/node_modules/kareem/index.js:289:15)
    at _init (/Users/lineus/dev/Help/mongoose5/node_modules/mongoose/lib/query.js:2010:5)
    at model.Document.init (/Users/lineus/dev/Help/mongoose5/node_modules/mongoose/lib/document.js:370:5)
    at completeOne (/Users/lineus/dev/Help/mongoose5/node_modules/mongoose/lib/query.js:1996:12)
    at cb (/Users/lineus/dev/Help/mongoose5/node_modules/mongoose/lib/query.js:2368:14)
    at /Users/lineus/dev/Help/mongoose5/node_modules/mongoose/lib/query.js:2454:16
    at /Users/lineus/dev/Help/mongoose5/node_modules/mongoose/lib/utils.js:418:16
    at session.endSession (/Users/lineus/dev/Help/mongoose5/node_modules/mongodb/lib/utils.js:400:74)
    at ClientSession.endSession (/Users/lineus/dev/Help/mongoose5/node_modules/mongodb-core/lib/sessions.js:69:41)
    at args.push (/Users/lineus/dev/Help/mongoose5/node_modules/mongodb/lib/utils.js:397:17)
    at handleCallback (/Users/lineus/dev/Help/mongoose5/node_modules/mongodb/lib/utils.js:128:55)
    at /Users/lineus/dev/Help/mongoose5/node_modules/mongodb/lib/collection.js:2296:12 name: 'ValidationError' }
^C
InspiredMacPro:Help lineus$ 

@jeremyml你是对的,我的例子不正确

schema.post('findOneAndUpdate', (result, next) =>{
  if (result.docField == 'invalidValue'){
    var validationError = new mongoose.Error.ValidationError(null);
    validationError.addError('docField', new mongoose.Error.ValidatorError({ message: 'Invalid' })); 
    return next(validationError);
  }
  // ...
});

ValidationError 是路径到 ValidatorError 实例的映射,因此您需要添加其中一个

此页面是否有帮助?
0 / 5 - 0 等级