2013-07-13 43 views
0

我在MongoDB中有两个集合,或者在猫鼬中有两个集合 - 用户和帐户。 用户架构获取子文档存在于不同集合中的mongodb文档的子文档

{ 
    account: [{type: db.Schema.Types.ObjectId , ref: 'Account'}] 
} 

帐户架构如下所示。

{network:String, 
firstName: String, 
lastName:String, 
networkId:Number, 
accessToken: String, 
accessTokenExpiration:Number, 
userId: {type: db.Schema.Types.ObjectId, ref: 'User'} 
} 

所以它基本上是用户和帐户之间的一对多关系。在express中,我有一个路径来获取具有参数userId的用户say/api/user的详细信息(匹配用户的mongodb objectId)。 我想返回此请求的整个用户对象。它也应包含子文档(即所有用户帐户)。

例如

{ "_id": "51e1b1b2993a51b0ce000005", "account": [ { 
"network": "Facebook", 
"networkId": xxxx, 
"accessToken": "yyyyy", 
"accessTokenExpiration": 11111, 
"firstName": "John", 
"lastName":"Doe" 
} ] } 

而不是

{ "_id": "51e1b1b2993a51b0ce000005", "account": [ "51e1b1b2993a51b0ce000004" ] } 

是否有MongoDB的或猫鼬的方式来此而实际上不必重复在用户对象的帐户阵列和在账户中收集搜索。

谢谢。

回答

1

猫鼬有population是专为这种情况下:

Users.findById(id) 
    .populate('account') 
    .exec(function (err, user) { 
    if (err) return next(err); 
    res.json(user); 
    }) 

或者,如果你使用express-mongoose插件:

res.send(Users.findById(id).populate('account')) 
+0

的作品就像一个魅力 – rOrlig