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
}
}