1

I have a data in mongo like root

 {'id':id,'name':'root','child'=['id1','id2','id3']}

chi1:

{'id':id1,'name':'chi1','child'=['id11','id12','id13']}

chi2

 {'id':id1,'name':'chi2','child'=['id21','id22','id23']}

chi11

 {'id':id1,'name':'chi11','child'=['id111','id112','id113']}

Now i want to show categories in templates like that :

root.name->chi1.name->chi11.name
         ->chi2.name

if we can query child fro the parent.

Vo Thanh Tung
  • 370
  • 1
  • 6
  • 20
  • Can you show us what you have tried so far? And your question is also not clear enough. – Shrabanee Aug 09 '16 at 09:03
  • As data from this question : http://stackoverflow.com/questions/38820071/create-object-parent-which-nested-children-in-mongoose i have tried to pass root to template, but i don't know how to query children information from the database such as chi1.name, chi11.name to show on template. – Vo Thanh Tung Aug 09 '16 at 09:15

2 Answers2

1

You can try following query:-

db.collName.find({_id : {$in:['id1','id2','id3']}}).toArray(function(err, results){
     console.log(results); //Will give you array of child results.
})

Now you can loop through the results array and get the corresponding names of child.

Refer $in-doc to know how to use $in in your query.

EDIT:-

Use something as below:-

function getResults(id, callback)
{ 
    db.collection.find({_id : parentId}).toArray(function(err, pres)
    {
        db.collName.find({_id : {$in:pres[0].child}}).toArray(
          function(err, results){
            console.log(results); //Will give you array of child results.
            console.log(pres[0]); // Result of root;

             callback(err, results, pres) ; //Return all the results
         })
     });
}

Hope this will help you.

Shrabanee
  • 2,706
  • 1
  • 18
  • 30
  • I have used mongoose which we can query object from the db by ID but the problem is if i only pass the root to the templates, i cannot to get children's information such as name to show in templates because in root object we just know id of children...so we have to back to controller go query again, it is impossible with jade templates. – Vo Thanh Tung Aug 09 '16 at 11:09
  • What you want to do exactly? You have to query twice, in your case. There is no other option. You can do both query in one function and then send all the results back and use. – Shrabanee Aug 09 '16 at 11:28
0

Mongoose - finding subdocuments by criteria with mongoose 4.0 populate is the best solution for query children object http://mongoosejs.com/docs/populate.html

Community
  • 1
  • 1
Vo Thanh Tung
  • 370
  • 1
  • 6
  • 20