我在貓鼬中有以下架構:
userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
team: {
type: Schema.Types.ObjectId, ref: 'Team',required:true
}
})
teamSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
coaches: []
})
我想加入這些集合,如果用戶 id 在coaches
字段中,它是團隊方案中的字符串數組。
加入後,我需要過濾以獲取在其coaches
屬性中具有特定 id 的用戶。
因此,populate 不適合這裡。我嘗試使用查找,但找不到正確的方法來執行此操作。對此有什麼想法嗎?
$match
coaches
數組中的用戶 ID$addFields
編輯coaches
數組$map
迭代coaches
數組循環$toObjectId
將字符串類型coaches
id轉換為 objectId 類型$lookup
與用戶集合let result await Team.aggregate([
{ $match: { coaches: "5a934e000102030405000001" } },
{
$addFields: {
coaches: {
$map: {
input: "$coaches",
in: { $toObjectId: "$$this" }
}
}
}
},
{
$lookup: {
from: "users", // update to correct users collection name
localField: "coaches",
foreignField: "_id",
as: "coaches"
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句