Imt*_*ekH 2 mongoose mongodb node.js
我有 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'}
});
Run Code Online (Sandbox Code Playgroud)
并且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"
}
Run Code Online (Sandbox Code Playgroud)
使用猫鼬获得这样的结果的最佳方法是什么?
{
_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
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过填充 User 来完成此操作。
您可以尝试在查询中填充 User :
代码 :
post.find().populate('User').exec(function(err,post){
console.log(post);
console.log(post.User);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3853 次 |
| 最近记录: |