我在Mongoose中定义了两个简单的模型,由两个模式客户端和City组成,我在客户端中将属性城市定义为ObjectId,ref:' city ',到目前为止还不错。
如果我查询客户端并希望通过城市的“省”属性进行筛选,则执行以下操作:
const client = await Client
.find({ name: "Gérard" })
.populate([{
path: 'city',
model: City,
match: { province: 'BA' }
}]);输出也很好:
{
"id": "627264e3ec261a883d42ead9",
"name": "Gérard",
"email": "gerard@depardieu.fr",
"date": "1948-12-27",
"active": true,
"city": {
"id": "627264e3ec261a883d42ead1",
"name": "Buenos Aires",
"province": "BA"
}
}但是,如果我输入一个不存在的城市的省代码:
const client = await Client
.find({ name: "Gérard" })
.populate([{
path: 'city',
model: City,
match: { province: 'CA' }
}]);它会回报我:
{
"id": "627264e3ec261a883d42ead9",
"name": "Gérard",
"email": "gerard@depardieu.fr",
"date": "1948-12-27",
"active": true,
"city": null
}我不希望在这个特定的场景中返回任何客户端实例,我也不知道如何使用Mongoose来避免这种行为,比如Spring数据,我从来不用担心这种行为。
有什么建议给我吗?
提前谢谢。
发布于 2022-06-14 14:07:55
我自己解决了这个问题,我不得不与猫鼬做一些更低的级别,使用聚合和查找。
const client = await Client.aggregate([
{
$match: { name: "Gérard" }
},
{
$lookup: {
from: City.collection.name,
pipeline: [
{
$match: {
province: 'BA'
}
}
], as: "city"
}
},
{
$unwind: "$city"
},
{
$match: {
city: { $ne: [] }
}
}
]);预期结果:
{
"id": "627264e3ec261a883d42ead9",
"name": "Gérard",
"email": "gerard@depardieu.fr",
"date": "1948-12-27",
"active": true,
"city": {
"id": "627264e3ec261a883d42ead1",
"name": "Buenos Aires",
"province": "BA"
}
}巫婆可以,客户名"Gérard“住在”布宜诺斯艾利斯“,位于省"BA”。
另一方面:
const client = await Client.aggregate([
{
$match: { name: "Gérard" }
},
{
$lookup: {
from: City.collection.name,
pipeline: [
{
$match: {
province: 'CA'
}
}
], as: "city"
}
},
{
$unwind: "$city"
},
{
$match: {
city: { $ne: [] }
}
}
]);一旦“布宜诺斯艾利斯”市不在"CA“省,什么也不返回。
请注意,传递给Client.aggregate()的数组在这里接收最后一个参数(作为对象):
{
$match: {
city: { $ne: [] }
}
}这告诉MongoDB,要返回数据,城市必须不等于空数组。
这个问题就解决了。
https://stackoverflow.com/questions/72167574
复制相似问题