2016-01-20 65 views
0

我有2个集合,它们处于一对多的关系。 如何使用猫鼬将相关数据作为嵌套文档获取?NodeJS,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 
    } 
} 
+2

的可能的复制[如何创建后填充在猫鼬子文档?](HTTP://计算器.com/questions/13026486/how-to-populate-a-sub-document-in-mongoose-after-creating-it) – chridam

+1

我会看看这个其他答案http://stackoverflow.com/questions/14363065 /猫鼬,MongoDB的查询,联接,但是-I-来从一个-SQL后台 – Autobat

回答

1

您可以通过填充用户来完成此操作。

你可以试着在查询中填入用户:

代码:

post.find().populate('User').exec(function(err,post){ 
    console.log(post); 
    console.log(post.User); 
})