【发布时间】:2016-04-25 23:01:42
【问题描述】:
我有 2 个集合,它们是一对多的关系。 如何使用 mongoose 将相关数据作为嵌套文档获取?
我有 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
}
}
【问题讨论】:
-
我会看看这个其他答案stackoverflow.com/questions/14363065/…