Reputation: 1262
I am trying to remove a document from an array. My schema is as so:
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
}]
})
I am trying to remove a doc by its _id within allocated_products
. Looked at a few examples and tried a few alternatives but can't get it working for me. So far I have this:
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);
})
This doesn't remove the doc and I get this error:
MongoError: exception: cannot use the part (allocated_products of allocated_products._id) to traverse the element
Is the only way to achieve this by doing a loop after a find() query? I would have thought there would have been a cleaner way.
Upvotes: 1
Views: 135
Reputation: 4055
As far as I know $pull doesn't support dot notation.
Try to do it with the following query:
var update = { $pull: { allocated_products: {_id: req.params.product } } };
Upvotes: 3