我在貓鼬中有以下架構:
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 不適合這里。我嘗試使用查找,但找不到正確的方法來執行此操作。對此有什么想法嗎?
uj5u.com熱心網友回復:
$matchcoaches陣列中的用戶 ID$addFields編輯coaches陣列$map迭代coaches陣列回圈$toObjectId將字串型別coachesid轉換為 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"
}
}
])
操場
uj5u.com熱心網友回復:
您正在使用Mongoosejs,我認為您不需要做很多事情,只需在它們之間建立適當的關系即可
teamSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
coaches: [{ type: Schema.Types.ObjectId, ref: 'User' }] // where User is model name
})
以及如何使用它們
Team.findOne({ name: 'team1' }).populate('coaches').exec();
// or with find
Team.find().populate('coaches').exec();
參考:https : //mongoosejs.com/docs/populate.html
根據評論更新
如果您需要傳遞查詢和投影,那么
Team.find().populate({
path: 'coaches',
match: { name: 'User1' },
select: 'name -_id' // only user name, remove _id
}).exec();
參考:https : //mongoosejs.com/docs/populate.html#query-conditions
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339586.html
