获取mongodb文档的子文档,其中子文档存在于不同的集合中

时间:2013-07-13 22:19:33

标签: mongodb express mongoose

我的mongodb中有两个集合,或者mongoose中有两个模式 - 用户和帐户。 用户架构

{
  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'}
}

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

e.g。

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

而不是

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

是否有mongodb或mongoose方法,而不必实际迭代User对象中的帐户数组并搜索帐户集合。

感谢。

1 个答案:

答案 0 :(得分:1)

Mongoose 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'))
相关问题