唯一选项不是 Mongoose 中的验证器

The unique Option is Not a Validator in Mongoose

我正在阅读 Mongoose 中的验证文档。但是我不明白 this part,谁能用不同的例子向我解释一下?

它说“初学者的一个常见陷阱是模式的唯一选项不是验证器。”这是什么意思?谢谢!

unique 选项用于在基础 MongoDB 集合中的指定字段上创建 unique indexmaxrequired 等 Mongoose 验证器选项在将查询发送到 MongoDB 之前在应用程序级别执行验证。以定义如下的事务模式为例:

const TransactionSchema = mongoose.Schema({
  transactionType: { type: String, required: true },
  amount: { type: Number, required: true, min: 1 },
}, { timestamps: true });

假设我们要向底层交易集合中插入一个新交易,如下所示:

await Transaction.create([{
   transactionType: 'credit',
   amount: 0, // amount < min thus mongoose throws a validation exception.
}]);

在上面的代码片段中,mongoose 将在您的应用程序中为 amount 属性 引发验证异常,并且请求不会命中数据库。然而,unique 选项不会以这种方式运行。它不验证应用程序级别的属性。它唯一的工作就是在你的数据库中建立一个唯一索引。

在没有建立索引的情况下,两个或多个文档最终可能会共享一个本应唯一的值。这个场景就是下面提到的'race condition'

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' }];
U1.create(dup, err => {
  // Race condition! This may save successfully, depending on whether
  // MongoDB built the index before writing the 2 docs.
});

但是,如果建立了唯一索引并且上面的操作是运行,MongoDB(不是mongoose)会报错。因此,为什么您应该等待 mongoose 在写入之前完成唯一索引的构建。