'Mongoose Returning null Reference of Property on Query
I have two simple models defined in Mongoose, composed of two schema Client and City, I have the property city defined in Client as a ObjectId, ref: 'City', so far so good.
If I query for a client and want also to filter by the 'province' property of City, I do it like this:
const client = await Client
.find({ name: "Gérard" })
.populate([{
path: 'city',
model: City,
match: { province: 'BA' }
}]);
And the output is just fine:
{
"id": "627264e3ec261a883d42ead9",
"name": "Gérard",
"email": "[email protected]",
"date": "1948-12-27",
"active": true,
"city": {
"id": "627264e3ec261a883d42ead1",
"name": "Buenos Aires",
"province": "BA"
}
}
Howerver, if I input a province code of a nonexistent city:
const client = await Client
.find({ name: "Gérard" })
.populate([{
path: 'city',
model: City,
match: { province: 'CA' }
}]);
It returns me this:
{
"id": "627264e3ec261a883d42ead9",
"name": "Gérard",
"email": "[email protected]",
"date": "1948-12-27",
"active": true,
"city": null
}
I don't want in this particular scenario, any instance of Client to be returned, and I don't know how to avoid this behavior with Mongoose, a behavior I never had to worry about with Spring Data for instance.
Somebody here told me to do something like this in my code:
const client = await Client
.find({ name: "Gérard" })
.populate([{
path: 'city',
model: City,
match: { province: 'CA' }
}]);
if(client && client.city){
return client; //or pass it to the response... whatever...
}
However, lets suppose this query is done over a collection with millions of clients, the code above is such a waste of resources that I won't even start the on what's wrong with it(ok, you can imagine how many clients not in province 'CA' the database server will send over to my app server just to be turned down....).
What I want is for no client to be returned at all, if that city/province doesn't match.
An example would be the analog SQL:
SELECT * FROM CLIENT JOIN CITY ON CITY.ID=CLIENT.CITY_ID WHERE CITY.PROVINCE = 'CA'
No client returned here, once the only client in database has its province = 'BA'.
So, how can it be done?
Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
