【问题标题】:Remove object from embedded array in MongoDB从 MongoDB 中的嵌入式数组中删除对象
【发布时间】:2016-01-06 06:50:16
【问题描述】:

我正在尝试从数组中删除一个文档。我的架构是这样的:

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

在 find() 查询之后执行循环是实现此目的的唯一方法吗?我原以为会有更清洁的方法。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    据我所知 $pull 不支持点符号。

    尝试使用以下查询:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 2020-12-20
      • 2021-07-03
      • 2021-04-19
      • 1970-01-01
      • 2013-03-16
      相关资源
      最近更新 更多