从MongoDB中的嵌入数组中删除对象

时间:2016-01-05 17:28:05

标签: node.js mongodb mongoose

我正在尝试从数组中删除文档。我的架构如下:

var FarmSchema = new Schema({
  _id: { type: String, unique: true, index: true }, //CPH FIELD
  cph:{type: String, unique: true},
  post_code: { type: String },
  robust_farm_type: { type: String },
  less_favoured_area_status: { type: String },
  organic_status: { type: Boolean },
  e_animal_records: { type: Boolean },
  e_ketosis_data: { type: Boolean },
  e_milk_conductivity_data: { type: Boolean },
  e_milk_data_yield: { type: Boolean },
  allocated_products : [{
    date : { type: Date, index: true, required: true  }, // Date - to be filtered on query . i.e date between x and y
    theraputic_group : { type: String, required: true }, //product category i.e. Antimicrobial
    volume : { type: Number, required: true } //Generic number to represent either quantity of tube or ml
    }]
})

我正在尝试在allocated_products中删除其_id文档。看了几个例子并尝试了一些替代方案,但无法让它为我工作。到目前为止,我有这个:

var query = { _id: req.params.id }; // id being the farm ID
  //Tried also {$elemMatch: {_id : '568bed3d4470f5e81519203b'}}
  var update = { $pull: { 'allocated_products._id': req.params.product }};

  Farm.findOneAndUpdate(query,update)
    .exec(function(err, customer) {
      if (err) return next(err);
      console.log(customer);
      res.json(customer);
    })

这不会删除文档,我收到此错误:

MongoError: exception: cannot use the part (allocated_products of allocated_products._id) to traverse the element

通过在f​​ind()查询后执行循环来实现此目的的唯一方法是什么?我原本以为会有更清洁的方式。

1 个答案:

答案 0 :(得分:2)

据我所知,$ pull不支持点表示法。

尝试使用以下查询执行此操作:

var update = { $pull: { allocated_products: {_id: req.params.product } } };