Thursday, 16 March 2017

Mongoose query for getting child and grand-child in a collection

What I have:

I have a collection in mongo which has many documents. The collection is called Users. For sample purposes I have shown 7 records of all.

{
    _id: _______________________,
    name: Mary    
},
{
    _id: _______________________,
    name: John,
    manager: objectId("id of Mary");
},
{
    _id: _______________________,
    name: Tim,
    manager: objectId("id of John");
},
{
    _id: _______________________,
    name: Tom,
    manager: objectId("id of John");
},
{
    _id: _______________________,
    name: Henry,
    manager: objectId("id of Tim");
},
{
    _id: _______________________,
    name: Mark,
    manager: objectId("id of Henry");
},
{
    _id: _______________________,
    name: Todd,
    manager: objectId("id of Mary");
}

By taking a look at the above data, you can see a relationship as follows:

                                 Mary
                                   |
                  -------------------------------------
                  |                                   |
                John                                Todd
                  |
      --------------------------
      |                         |
     Tim                       Tom
      |
    Henry
      |
    Mark

What I want:

I want a mongoose query, which returns me all the records with its child and grand-child. So, for example, if I want to have all the users under John including John, then my output should look something like:

{
    _id: _______________________,
    name: John,
    manager: objectId("id of Mary");
},
{
    _id: _______________________,
    name: Tim,
    manager: objectId("id of John");
},
{
    _id: _______________________,
    name: Tom,
    manager: objectId("id of John");
},
{
    _id: _______________________,
    name: Henry,
    manager: objectId("id of Tim");
},
{
    _id: _______________________,
    name: Mark,
    manager: objectId("id of Henry");
}

What I don't want:

I know that data is relational, so some people may advice me that I should use a relational database. But right now I am trying to learn mongodb and Node.js. So, I would like to stick with mongodb.

I also know that it is possible to have a collection which holds all the data like this:

var ManagerSchema = new Schema({
   manager_name: String,
   users: [users]
}

var UserSchema = new Schema({
   user_name: String
})

But I don't want above mentioned stuff.

I just want to have only one collection and the data will be relational.



via Vishal

No comments:

Post a Comment