mongoose delete hierarchical data

Viewed 31

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.

1 Answers
let arr = [
    {"id": 2, "parentId": 1, "name": "Fruits"},
    {"id": 3, "parentId": 2, "name": "apple"},
    {"id": 4, "parentId": 2, "name": "orange"},
    {"id": 5, "parentId": 2, "name": "tomato"},
    {"id": 6, "parentId": 1, "name": "Vegetables"},
    {"id": 7, "parentId": 6, "name": "carrot"},
    {"id": 8, "parentId": 6, "name": "cabbage"},
    {"id": 9, "parentId": 6, "name": "potato"},
    {"id": 10, "parentId": 6, "name": "lettuce"},
    {"id": 11, "parentId": 0, "name": "Cars"},
    {"id": 13, "parentId": 8, "name": "Cars"},
    {"id": 1, "parentId": 0, "name": "Foods"},
];

//Into a tree  parentId=0 Is a top
function convert(arr, id = 0) {
    let res = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].parentId == id) {
            let obj = {};
            obj.idIP = arr[i].id;
            obj.ip = arr[i];
            res.push(obj);
            let func = convert.bind();
            obj.children = func(arr, arr[i].id);
        }
    }
    return res;
}
Related