我有 2 个集合,它们是一对多的关系。
如何使用猫鼬获取相关数据作为嵌套文档?
我有 2 个模式,它们是这样相关的..
var userSchema = mongoose.Schema({
name : String,
age : Number,
});
var postSchema = mongoose.Schema({
title: String,
body: String,
user: {type: mongoose.Schema.Types.ObjectId, ref:'User'}
});
并且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"
}
使用猫鼬获得这样的结果的最佳方法是什么?
{
_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
}
}