Mongoose,在update中验证数组中的$ pull项

时间:2017-07-31 19:49:30

标签: node.js mongodb mongoose

给出以下架构:

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
});

我想验证作者数组是否包含至少一个类型为==' FOO'

的对象。

这意味着这应该失败:

  var update = {
    $pull: {
      authors: {
        name: 'Mark'
      }
    }
  };

  Book.findByIdAndUpdate(book._id, update, {runValidators: true}, function(err, book) {
    ...
  });

如果文件目前是:

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

我试图在作者路径上定义验证器:

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

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

我完全理解为什么,因为在更新中,doc没有加载到内存中。

话虽如此,这是一个正确的'做这种验证的方法?也许首先查询doc,然后手动删除/添加元素,然后调用save?

0 个答案:

没有答案