这是我的Product Schema
const product = mongoose.Schema({
name: {
type: String,
},
category:{
type: ObjectId,
ref: Category
}
}
我想根据来自前端的过滤器返回产品。让我们考虑两个类别Summer
和Winter
。当用户想要按Summer
类别过滤产品时,将对http://localhost:8000/api/products?category=summer
进行api调用
现在我的问题是,我如何过滤,因为从前端我得到类别名称,有产品模式中的ObjectId。我的尝试:Project.find({category:categoryName})
如果我理解正确的话,您可以尝试以下查询之一:
第一个是使用管道到$lookup
来匹配category
和name
,就像这样:
yourModel.aggregate([
{
"$lookup": {
"from": "category",
"let": {
"category": "$category",
},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$id",
"$$category"
]
},
{
"$eq": [
"$name",
"Summer"
]
}
]
}
}
}
],
"as": "categories"
}
},
{
"$match": {
"categories": {
"$ne": []
}
}
}
])
例子
另一种方法是使用正常的$lookup
,然后使用join返回的$filter
数组。
yourModel.aggregate([
{
"$lookup": {
"from": "category",
"localField": "category",
"foreignField": "id",
"as": "categories"
}
},
{
"$match": {
"categories": {
"$ne": []
}
}
},
{
"$set": {
"categories": {
"$filter": {
"input": "$categories",
"as": "c",
"cond": {
"$eq": [
"$$c.name",
"Summer"
]
}
}
}
}
}
])
例子
注意这两个查询如何使用$match: { categories: { $ne : []}}
,这是因为如果查找没有找到任何结果,它返回一个空数组。顺便说一下,这个阶段是可选的。
还可以添加$unwind
或$arrayElemAt index 0
或其他任何值,从数组中只获得一个值。
同样,在mongoose中,您只需要将"Summer"
替换为您的变量。