验证

在我们深入了解验证语法之前,请牢记以下规则:

  • 验证是在 模式类型 中定义的。
  • 验证是 中间件。默认情况下,Mongoose 在每个模式上注册验证作为 pre('save') 钩子。
  • 验证始终作为第一个 pre('save') 钩子运行。这意味着验证不会在 pre('save') 钩子中的任何更改上运行。
  • 您可以通过设置 validateBeforeSave 选项来禁用在保存之前自动执行验证。
  • 您可以使用 doc.validate()doc.validateSync() 手动运行验证。
  • 您可以使用 doc.invalidate(...) 手动将字段标记为无效(导致验证失败)。
  • 验证器不会在未定义的值上运行。唯一的例外是 required 验证器
  • 当您调用 Model#save 时,Mongoose 还会运行子文档验证。如果发生错误,您的 Model#save promise 会拒绝。
  • 验证是可自定义的。
const schema = new Schema({
  name: {
    type: String,
    required: true
  }
});
const Cat = db.model('Cat', schema);

// This cat has no name :(
const cat = new Cat();

let error;
try {
  await cat.save();
} catch (err) {
  error = err;
}

assert.equal(error.errors['name'].message,
  'Path `name` is required.');

error = cat.validateSync();
assert.equal(error.errors['name'].message,
  'Path `name` is required.');

内置验证器

Mongoose 有几个内置验证器。

上面的每个验证器链接都提供了有关如何启用它们以及自定义其错误消息的更多信息。

const breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});
const Breakfast = db.model('Breakfast', breakfastSchema);

const badBreakfast = new Breakfast({
  eggs: 2,
  bacon: 0,
  drink: 'Milk'
});
let error = badBreakfast.validateSync();
assert.equal(error.errors['eggs'].message,
  'Too few eggs');
assert.ok(!error.errors['bacon']);
assert.equal(error.errors['drink'].message,
  '`Milk` is not a valid enum value for path `drink`.');

badBreakfast.bacon = 5;
badBreakfast.drink = null;

error = badBreakfast.validateSync();
assert.equal(error.errors['drink'].message, 'Path `drink` is required.');

badBreakfast.bacon = null;
error = badBreakfast.validateSync();
assert.equal(error.errors['bacon'].message, 'Why no bacon?');

自定义错误消息

您可以在模式中配置单个验证器的错误消息。有两种等效的方法可以设置验证器错误消息:

  • 数组语法:min: [6, 'Must be at least 6, got {VALUE}']
  • 对象语法:enum: { values: ['Coffee', 'Tea'], message: '{VALUE} is not supported' }

Mongoose 还支持错误消息的基本模板。Mongoose 将 {VALUE} 替换为正在验证的值。

const breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Must be at least 6, got {VALUE}'],
    max: 12
  },
  drink: {
    type: String,
    enum: {
      values: ['Coffee', 'Tea'],
      message: '{VALUE} is not supported'
    }
  }
});
const Breakfast = db.model('Breakfast', breakfastSchema);

const badBreakfast = new Breakfast({
  eggs: 2,
  drink: 'Milk'
});
const error = badBreakfast.validateSync();
assert.equal(error.errors['eggs'].message,
  'Must be at least 6, got 2');
assert.equal(error.errors['drink'].message, 'Milk is not supported');

unique 选项不是验证器

初学者常犯的一个错误是,模式的 unique 选项不是验证器。它是一个用于构建 MongoDB 唯一索引 的便捷助手。有关更多信息,请参见 常见问题解答

const uniqueUsernameSchema = new Schema({
  username: {
    type: String,
    unique: true
  }
});
const U1 = db.model('U1', uniqueUsernameSchema);
const U2 = db.model('U2', uniqueUsernameSchema);

const dup = [{ username: 'Val' }, { username: 'Val' }];
// Race condition! This may save successfully, depending on whether
// MongoDB built the index before writing the 2 docs.
U1.create(dup).
  then(() => {
  }).
  catch(err => {
  });

// You need to wait for Mongoose to finish building the `unique`
// index before writing. You only need to build indexes once for
// a given collection, so you normally don't need to do this
// in production. But, if you drop the database between tests,
// you will need to use `init()` to wait for the index build to finish.
U2.init().
  then(() => U2.create(dup)).
  catch(error => {
    // `U2.create()` will error, but will *not* be a mongoose validation error, it will be
    // a duplicate key error.
    // See: https://masteringjs.io/tutorials/mongoose/e11000-duplicate-key
    assert.ok(error);
    assert.ok(!error.errors);
    assert.ok(error.message.indexOf('duplicate key error') !== -1);
  });

自定义验证器

如果内置验证器不够用,您可以定义自定义验证器以满足您的需求。

自定义验证是通过传递一个验证函数来声明的。您可以在 SchemaType#validate() API 文档 中找到有关如何执行此操作的详细说明。

const userSchema = new Schema({
  phone: {
    type: String,
    validate: {
      validator: function(v) {
        return /\d{3}-\d{3}-\d{4}/.test(v);
      },
      message: props => `${props.value} is not a valid phone number!`
    },
    required: [true, 'User phone number required']
  }
});

const User = db.model('user', userSchema);
const user = new User();
let error;

user.phone = '555.0123';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
  '555.0123 is not a valid phone number!');

user.phone = '';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
  'User phone number required');

user.phone = '201-555-0123';
// Validation succeeds! Phone number is defined
// and fits `DDD-DDD-DDDD`
error = user.validateSync();
assert.equal(error, null);

异步自定义验证器

自定义验证器也可以是异步的。如果您的验证器函数返回一个 promise(如 async 函数),mongoose 将等待该 promise 完成。如果返回的 promise 被拒绝,或以 false 值完成,Mongoose 将认为这是一个验证错误。

const userSchema = new Schema({
  name: {
    type: String,
    // You can also make a validator async by returning a promise.
    validate: () => Promise.reject(new Error('Oops!'))
  },
  email: {
    type: String,
    // There are two ways for an promise-based async validator to fail:
    // 1) If the promise rejects, Mongoose assumes the validator failed with the given error.
    // 2) If the promise resolves to `false`, Mongoose assumes the validator failed and creates an error with the given `message`.
    validate: {
      validator: () => Promise.resolve(false),
      message: 'Email validation failed'
    }
  }
});

const User = db.model('User', userSchema);
const user = new User();

user.email = '[email protected]';
user.name = 'test';

let error;
try {
  await user.validate();
} catch (err) {
  error = err;
}
assert.ok(error);
assert.equal(error.errors['name'].message, 'Oops!');
assert.equal(error.errors['email'].message, 'Email validation failed');

验证错误

验证失败后返回的错误包含一个 errors 对象,其值为 ValidatorError 对象。每个 ValidatorError 都有 kindpathvaluemessage 属性。ValidatorError 也可能具有 reason 属性。如果验证器中抛出了错误,此属性将包含抛出的错误。

const toySchema = new Schema({
  color: String,
  name: String
});

const validator = function(value) {
  return /red|white|gold/i.test(value);
};
toySchema.path('color').validate(validator,
  'Color `{VALUE}` not valid', 'Invalid color');
toySchema.path('name').validate(function(v) {
  if (v !== 'Turbo Man') {
    throw new Error('Need to get a Turbo Man for Christmas');
  }
  return true;
}, 'Name `{VALUE}` is not valid');

const Toy = db.model('Toy', toySchema);

const toy = new Toy({ color: 'Green', name: 'Power Ranger' });

let error;
try {
  await toy.save();
} catch (err) {
  error = err;
}

// `error` is a ValidationError object
// `error.errors.color` is a ValidatorError object
assert.equal(error.errors.color.message, 'Color `Green` not valid');
assert.equal(error.errors.color.kind, 'Invalid color');
assert.equal(error.errors.color.path, 'color');
assert.equal(error.errors.color.value, 'Green');

// If your validator throws an exception, mongoose will use the error
// message. If your validator returns `false`,
// mongoose will use the 'Name `Power Ranger` is not valid' message.
assert.equal(error.errors.name.message,
  'Need to get a Turbo Man for Christmas');
assert.equal(error.errors.name.value, 'Power Ranger');
// If your validator threw an error, the `reason` property will contain
// the original error thrown, including the original stack trace.
assert.equal(error.errors.name.reason.message,
  'Need to get a Turbo Man for Christmas');

assert.equal(error.name, 'ValidationError');

强制转换错误

在运行验证器之前,Mongoose 会尝试将值强制转换为正确的类型。此过程称为强制转换文档。如果给定路径的强制转换失败,则 error.errors 对象将包含一个 CastError 对象。

强制转换在验证之前运行,如果强制转换失败,则不会运行验证。这意味着您的自定义验证器可以假设 vnullundefined 或您的模式中指定类型的实例。

const vehicleSchema = new mongoose.Schema({
  numWheels: { type: Number, max: 18 }
});
const Vehicle = db.model('Vehicle', vehicleSchema);

const doc = new Vehicle({ numWheels: 'not a number' });
const err = doc.validateSync();

err.errors['numWheels'].name; // 'CastError'
// 'Cast to Number failed for value "not a number" at path "numWheels"'
err.errors['numWheels'].message;

默认情况下,Mongoose 强制转换错误消息看起来像 Cast to Number failed for value "pie" at path "numWheels"。您可以通过 SchemaType 上的 cast 选项覆盖 Mongoose 的默认强制转换错误消息,如下所示。

const vehicleSchema = new mongoose.Schema({
  numWheels: {
    type: Number,
    cast: '{VALUE} is not a number'
  }
});
const Vehicle = db.model('Vehicle', vehicleSchema);

const doc = new Vehicle({ numWheels: 'pie' });
const err = doc.validateSync();

err.errors['numWheels'].name; // 'CastError'
// "pie" is not a number
err.errors['numWheels'].message;

Mongoose 的强制转换错误消息模板支持以下参数:

  • {PATH}:强制转换失败的路径
  • {VALUE}:强制转换失败的值的字符串表示
  • {KIND}:Mongoose 尝试强制转换到的类型,例如 'String''Number'

您还可以定义一个函数,Mongoose 将调用该函数以获取强制转换错误消息,如下所示。

const vehicleSchema = new mongoose.Schema({
  numWheels: {
    type: Number,
    cast: [null, (value, path, model, kind) => `"${value}" is not a number`]
  }
});
const Vehicle = db.model('Vehicle', vehicleSchema);

const doc = new Vehicle({ numWheels: 'pie' });
const err = doc.validateSync();

err.errors['numWheels'].name; // 'CastError'
// "pie" is not a number
err.errors['numWheels'].message;

全局模式类型验证

除了在单个模式路径上定义自定义验证器之外,您还可以配置一个自定义验证器,以在给定 SchemaType 的每个实例上运行。例如,以下代码演示了如何使空字符串 '' 成为所有字符串路径的无效值。

// Add a custom validator to all strings
mongoose.Schema.Types.String.set('validate', v => v == null || v > 0);

const userSchema = new Schema({
  name: String,
  email: String
});
const User = db.model('User', userSchema);

const user = new User({ name: '', email: '' });

const err = await user.validate().then(() => null, err => err);
err.errors['name']; // ValidatorError
err.errors['email']; // ValidatorError

嵌套对象上的必需验证器

在 mongoose 中定义嵌套对象上的验证器很棘手,因为嵌套对象不是完全成熟的路径。

let personSchema = new Schema({
  name: {
    first: String,
    last: String
  }
});

assert.throws(function() {
  // This throws an error, because 'name' isn't a full fledged path
  personSchema.path('name').required(true);
}, /Cannot.*'required'/);

// To make a nested object required, use a single nested schema
const nameSchema = new Schema({
  first: String,
  last: String
});

personSchema = new Schema({
  name: {
    type: nameSchema,
    required: true
  }
});

const Person = db.model('Person', personSchema);

const person = new Person();
const error = person.validateSync();
assert.ok(error.errors['name']);

更新验证器

在上面的示例中,您了解了文档验证。Mongoose 还支持 update()updateOne()updateMany()findOneAndUpdate() 操作的验证。更新验证器默认情况下是关闭的 - 您需要指定 runValidators 选项。

要打开更新验证器,请为 update()updateOne()updateMany()findOneAndUpdate() 设置 runValidators 选项。注意:更新验证器默认情况下是关闭的,因为它们有一些注意事项。

const toySchema = new Schema({
  color: String,
  name: String
});

const Toy = db.model('Toys', toySchema);

Toy.schema.path('color').validate(function(value) {
  return /red|green|blue/i.test(value);
}, 'Invalid color');

const opts = { runValidators: true };

let error;
try {
  await Toy.updateOne({}, { color: 'not a color' }, opts);
} catch (err) {
  error = err;
}

assert.equal(error.errors.color.message, 'Invalid color');

更新验证器和 this

更新验证器和文档验证器之间存在一些关键差异。在下面的颜色验证函数中,当使用文档验证时,this 指的是正在验证的文档。但是,当运行更新验证器时,this 指的是查询对象而不是文档。由于查询有一个整洁的 .get() 函数,您可以获取要更新的属性的更新值。

const toySchema = new Schema({
  color: String,
  name: String
});

toySchema.path('color').validate(function(value) {
  // When running in `validate()` or `validateSync()`, the
  // validator can access the document using `this`.
  // When running with update validators, `this` is the Query,
  // **not** the document being updated!
  // Queries have a `get()` method that lets you get the
  // updated value.
  if (this.get('name') && this.get('name').toLowerCase().indexOf('red') !== -1) {
    return value === 'red';
  }
  return true;
});

const Toy = db.model('ActionFigure', toySchema);

const toy = new Toy({ color: 'green', name: 'Red Power Ranger' });
// Validation failed: color: Validator failed for path `color` with value `green`
let error = toy.validateSync();
assert.ok(error.errors['color']);

const update = { color: 'green', name: 'Red Power Ranger' };
const opts = { runValidators: true };

error = null;
try {
  await Toy.updateOne({}, update, opts);
} catch (err) {
  error = err;
}
// Validation failed: color: Validator failed for path `color` with value `green`
assert.ok(error);

更新验证器仅在更新的路径上运行

另一个关键区别是更新验证器仅在更新中指定的路径上运行。例如,在下面的示例中,由于在更新操作中没有指定“name”,因此更新验证将成功。

当使用更新验证器时,required 验证器在您尝试显式 $unset 键时才会失败。

const kittenSchema = new Schema({
  name: { type: String, required: true },
  age: Number
});

const Kitten = db.model('Kitten', kittenSchema);

const update = { color: 'blue' };
const opts = { runValidators: true };
// Operation succeeds despite the fact that 'name' is not specified
await Kitten.updateOne({}, update, opts);

const unset = { $unset: { name: 1 } };
// Operation fails because 'name' is required
const err = await Kitten.updateOne({}, unset, opts).then(() => null, err => err);
assert.ok(err);
assert.ok(err.errors['name']);

更新验证器仅在某些操作时运行

最后值得注意的是,更新验证器在以下更新操作上运行:

  • $set
  • $unset
  • $push
  • $addToSet
  • $pull
  • $pullAll

例如,下面的更新将成功,无论 number 的值如何,因为更新验证器会忽略 $inc

此外,$push$addToSet$pull$pullAll 验证不会对数组本身运行任何验证,只会对数组的单个元素运行验证。

const testSchema = new Schema({
  number: { type: Number, max: 0 },
  arr: [{ message: { type: String, maxlength: 10 } }]
});

// Update validators won't check this, so you can still `$push` 2 elements
// onto the array, so long as they don't have a `message` that's too long.
testSchema.path('arr').validate(function(v) {
  return v.length < 2;
});

const Test = db.model('Test', testSchema);

let update = { $inc: { number: 1 } };
const opts = { runValidators: true };

// There will never be a validation error here
await Test.updateOne({}, update, opts);

// This will never error either even though the array will have at
// least 2 elements.
update = { $push: [{ message: 'hello' }, { message: 'world' }] };
await Test.updateOne({}, update, opts);

下一步

既然我们已经介绍了 Validation,让我们看一下 Middleware