I am trying to use query search in mongoose when user hast array of objects with different postalCodes.
And I have an object which is called Job.
At job I have postalCode as String.
What I want to achieve it is for each postalCode from users to slice the postalCode on jobs and if possible to match them.
Problem it is that always it is returning empty but in case it should match with the job and return it.
User it is always the logged in user.
So user is the given input to search into the collection of jobs
Here is my Code of 1 user.
"searchFilter" : {
"remote" : 0,
"data" : [
{
"country" : "DEU",
"searchActive" : false,
"postalCode" : "123",
"available" : {
"$date" : 1664955924380
}
},
{
"country" : "DEU",
"searchActive" : false,
"postalCode" : "850",
"available" : {
"$date" : 1667165151744
}
}
]
},
And this is the job.
"postalCode" : "12345",
"country" : "DEU",
And this is my actual query search.
let job = await Job.find({
$or: user.searchFilter.data.map((user) => user.postalCode)
.map((postalCode) => ( {
yearSubstring: { $substr: [ "$postalCode", 0, postalCode.length ] },
}))
});
if (!job) {
res.status(204).json({ error: "No Data" });
return;
}
return res.status(200).send(job);
2
Answers
If I understand correctly, what you want is close to this:
unwind
to divide itsdata
to different documentsjobs
for eachdata
itemdata
items that has ajob
.$group
all the relevantdata
items of theuser
to one document (can be seen on the playground link below)See how it works on the playground example
You can simply use
$in
operator to find the string from a provided array of strings,Playground
If you want to search the substring or inside the string then you can use
$regex
operator,Playground