Mongoose,在更新中validation数组中的$ pull项

鉴于以下模式:

var BookSchema = new Schema({ name: { type: String, required: true, unique: true }, description: { type: String, required: false }, authors: [AuthorSchema] }); var AuthorSchema = new Schema({ name: { type: String, required: true } type: { type: String, enum: ['FOO', 'BAR'], required: false } }, { _id: false }); 

我想validation作者数组至less包含一个types=='FOO'的对象。

这意味着这应该失败:

  var update = { $pull: { authors: { name: 'Mark' } } }; Book.findByIdAndUpdate(book._id, update, {runValidators: true}, function(err, book) { ... }); 

如果该文件目前是:

 { name: 'foo', authors: [{ name: 'Mark', type: 'FOO' }] } 

我试图在作者path上定义一个validation器:

 BookSchema.path('authors').validate(function(authors) { return authors.filter(function(author) { return author.type === 'FOO'; }).length > 0; }); 

问题是validation在update语句中的数组上运行而不是实际文档中的数组。

我完全理解,为什么,由于在更新文件没有加载到内存的事实。

这就是说,这是一种“正确”的方式来做这种validation? 也许先查询文档,然后手动删除/添加元素,然后调用保存?