2

I have 2 collections and they are in one-to-many relationship. How can i get related data as nested document using mongoose?

I have 2 schemas and they are related like this..

var userSchema = mongoose.Schema({
  name : String,
  age : Number,
});

var postSchema = mongoose.Schema({
  title: String,
  body: String,
  user: {type: mongoose.Schema.Types.ObjectId, ref:'User'}
});

and there are data in mongodb..

//user:
{
  _id:"5694934cab2816601db06291", 
  name:"John", 
  age:16
},
{
  _id:"5694934cab2816601db06292", 
  name:"Kim", 
  age:61
}

//post : 
{
  _id:"569494e5ab2816601db06293",
  title:"hi",
  body:"nice to meet you",
  user:"5694934cab2816601db06291"
},
{
  _id:"569494e5ab2816601db06294", 
  title:"hello",
  body:"how are you",
  user:"5694934cab2816601db06292"
}

What is the best way to get results like this using mongoose?

{
  _id:"569494e5ab2816601db06293", 
  title:"hi", 
  body:"nice to meet you", 
  user:{
         _id:"569494e5ab2816601db06294",
         name:"John", 
         age:16
  }
},
{
  _id:"569494e5ab2816601db06294",
  title:"hello",
  body:"how are you",
  user:{
         _id:"569494e5ab2816601db06292",
         name:"Kim", 
         age:61
  }
}
ImtaekH
  • 67
  • 1
  • 6
  • 2
    Possible duplicate of [How to populate a sub-document in mongoose after creating it?](http://stackoverflow.com/questions/13026486/how-to-populate-a-sub-document-in-mongoose-after-creating-it) – chridam Jan 20 '16 at 07:56
  • 1
    i would take a look at this other answer http://stackoverflow.com/questions/14363065/mongoose-mongodb-query-joins-but-i-come-from-a-sql-background – Autobat Jan 20 '16 at 07:59

1 Answers1

5

You can do this by populating User.

You can try to populate User in your query :

Code :

post.find().populate('User').exec(function(err,post){
    console.log(post);
    console.log(post.User);
})
Md Nazmul Hossain
  • 2,768
  • 5
  • 26
  • 49