I have a collection containing a bunch of schemas that looks something like this:
_id: 1
parent: null
_id: 2
parent: 1
_id: 3
parent: 1
_id: 4
parent: 2
(_id and parent are of type ObjectID and dont actually look like this)
this translates to a hierarchy looking like this:
-1
-2
-4
-3
Im trying to delete an item from this hierarchy, lets say item 1 (_id: 1), this means I also need to delete all related items (2,3,4). I dont know how to do this (Im guessing the most efficient thing to do would be use Aggregate), can someone please help me or point me in the right direction? Thanks in advance!
[EDIT]
remove(idToRemove)
function remove(node){
Item.findByIdAndDelete(node).then(()=>{
Item.find({parent: mongoose.Types.ObjectId(node)}).select('_id').then((d)=>{
d.forEach(e => {
remove(e._id)
});
})
})
}
I managed to get this thing working however this pulls data multiple times, which is obviously not optimal.