0

I have tree stucture like this:

[{
...,
childCode: [
    ...,
    childCode: []
]
},
{...,
childCode:[
]
}
]

And I want to delete all child codes...

I am able to do it wit recusion:

In my my code:

removeChild(code.childCode);

return res.json({
 message: "Code deleted!"
});

recusion function:

function removeChild(code) {
    if (code.length == 0) {
        console.log("done");
    } else
    {
        code.forEach(function (code) {
            setTimeout(function () {

                code.remove();

                removeChild(code.childCode);
            }, 100);


        });
    }
}

Is this right way to do this?

Vladimir Djukic
  • 2,042
  • 7
  • 29
  • 60

1 Answers1

0

Suppose you have a tree like this:

__A
 |_B
 | |_C
 |
 |_D

This is how you save it in the database according to the materialized path pattern:

[
  { _id: 'A', path: 'A' },
  { _id: 'B', path: 'A/B' },
  { _id: 'C', path: 'A/B/C' },
  { _id: 'D', path: 'A/D' }
]

You can query the whole tree like this:

Node
  .find({ path: { $regex: /A/ } })
  .exec()
  .then(...);

Note: after querying, you can convert it to your JSON structure like this


and remove whole tree like this:

Node
  .remove({ path: { $regex: /A/ } })
  .exec()
  .then(...);
Community
  • 1
  • 1
willie17
  • 901
  • 8
  • 12