先上表結構:
ui
我要根據waitgets的giftId關聯查詢giftkinds裏的信息。
一開始主鍵外鍵搞錯了,由於主集合是waitgets,因此轉換字段數據類型時要該變主集合的類型。並且我還要根據uid過濾用戶。因此寫了下面的查詢方式。spa
db.waitgets.aggregate([ {$match:{uid:"5ea84896ab117b1c9c33ba3d"}}, { "$project": { "giftId": { "$toObjectId": "$giftId" } } }, { $lookup: { from: "giftkinds", localField: "giftId", foreignField: "_id", as: "child" } } ]);
在egg.js的項目裏,副集合的名字也要小寫才行。3d
let waitGet = await ctx.model.WaitGet.aggregate([ { $match: { uid: '5ea84896ab117b1c9c33ba3d' } }, { "$project": { "giftId": { "$toObjectId": "$giftId" } } }, { $lookup: { from: "giftkinds", localField: "giftId", foreignField: "_id", as: "child" } } ])