猫鼬唯一验证器
如何使用这个插件:
1) npm install --save mongoose-unique-validator
2)在您的架构中遵循本指南:
// declare this at the top
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
// exampleSchema = mongoose.Schema({}) etc...
exampleSchema.plugin(uniqueValidator);
// module.exports = mongoose.model(...) etc....
3)猫鼬方法
当使用像findOneAndUpdate
你这样的方法时,你需要传递这个配置对象:
{ runValidators: true, context: 'query' }
ie. User.findOneAndUpdate(
{ email: 'old-email@example.com' },
{ email: 'new-email@example.com' },
{ runValidators: true, context: 'query' },
function(err) {
// ...
}
4) 附加选项
不区分大小写
在您的架构中使用 uniqueCaseInsensitive 选项
ie. email: { type: String, index: true, unique: true, required: true, uniqueCaseInsensitive: true }
自定义错误消息
ie. exampleSchema.plugin(uniqueValidator, { message: 'Error, expected {PATH} to be unique.' });
现在,您可以在模式中添加/删除唯一属性,而无需担心重新启动 mongo、删除数据库或创建索引。
注意事项(来自文档):
因为我们依赖异步操作来验证数据库中是否存在一个文档,所以有可能两个查询同时执行,都返回0,然后都插入到MongoDB中。
除了自动锁定集合或强制单个连接之外,没有真正的解决方案。
对于我们的大多数用户来说,这不是问题,但需要注意的边缘情况。