I have a complex model that looks something like this: (I'm omitting none important attributes for simplicity)
var propertyModel = mongoose.Schema({ name: String });
var bodyPart = mongoose.Schema({
name:String,
sortOrder:Number,
category: [{
name:String,
properties: [{type:mongoose.Schema.Types.ObjectId,ref:"Property"}]
}]
});
var specie = mongoose.Schema({
species: String,
properties: [{propertyId:{type:mongoose.Schema.Types.ObjectId,ref:"Property"}, value:String}]
});
So for example a bodyPart is "Head" and it has category "Face","Eyes","Antennae" and each category has multiple properties.
When I want to remove a property from the DB I also want to remove all the references from the Specie and the BodyPart objects.
For this I am using the middleware functionality in Mongoose. The Specie part works great like this:
propertyModel.pre("remove",function(next){
console.log("Pre remove 1");
this.model('Specie').update(
{properties: {$elemMatch: {propertyId:this._id}}},
{$pull: {properties: {propertyId:this._id}}},
{multi: true},
next
);
});
However I cannot seem to find the correct way to reference category.properties in the BodyPart object.
I tried this:
propertyModel.pre("remove",function(next){
console.log("Pre remove 2");
this.model('BodyPart').update(
{'category.properties': this._id},
{$pull: {'category.properties': this._id}},
{multi: false},
next
);
});
But that does not seem to work...
MongoError: cannot use the part (category of category.properties) to traverse the element
What is the correct way to reference the property ID in this case?