簡體   English   中英

獲取子文件夾存在於不同集合中的mongodb文檔的子文檔

[英]Getting subdocuments of a mongodb document where the subdocument exists in different collection

我的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'}
}

因此,它基本上是用戶和帳戶之間的一對多關系。 在快遞中,我有一條路線來獲取用戶的詳細信息,例如/ api / user和參數userId(與User的mongodb objectId匹配)。 我想為此請求返回整個用戶對象。 它也應該包含子文檔(即所有用戶帳戶)。

例如

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

而不是

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

是否有一種mongodb或mongoose的方法,而不必實際迭代User對象中的account數組並在accounts集合中進行搜索。

謝謝。

貓鼬有專門為這種情況設計的種群

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'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM