15

Any idea how to model a Tree document in Mongoose Schema?

var TreeSchema = new Schema({
    "Non-leafNode": {
        "children": [
            {
                "type": "NodeElement"
            }
        ]
    },
    "NodeElement": {
        // one of them is required. not both.
        "elem": {
            "type": "LeafNode"
        },
        "elem2": {
            "type": "Non-leafNode"
        }
    },
    "LeafNode": {}
});

How could one model this? The entire Tree is one document (ideally).

1 Answer 1

28

From https://groups.google.com/forum/#!topic/mongoose-orm/0yUVXNyprx8:

By design, it might work. There's no tests for this. I have Schema#add in there for this purpose, to produce recursive references:

var Tasks = new Schema();
Tasks.add({
   title     : String
 , subtasks  : [Tasks]
});

So you need to construct the recursion step by step.

2
  • How would you populate that? In case you want to get all the information of all descendants of all tasks
    – ERP
    Commented Aug 2, 2020 at 8:24
  • 2
    It's all in a single Mongo document, so it's already populated
    – w00t
    Commented Aug 2, 2020 at 10:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.