我在mongoose中有以下模式:
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
with users collection
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"
}
}
])
游乐场
你正在使用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