I need help querying my MongoDB using JavaScript as I am only getting one result when I should be utilizing the $or
operator.
The frontend sends a string, which I then split by spaces to search for matches in the database based on skills, location, and name. For instance, if a user searches for "PHP", it should return all users with PHP as a skill, even if they have other skills. Here is an example of the data:
Data:
{
"_id":"1",
"skills": ["PHP"],
"name":"You"
}
{
"_id":"2",
"skills": ["PHP", "Javascript"],
"name":"Me"
}
The code:
exports.search = async (req, res, next) => {
try {
const escapeChar = escapeString(req.body.query);
const searchQueries = escapeChar.split(' ');
let result;
for (let i in searchQueries) {
const ret = async () => {
const pattern = new RegExp(searchQueries[i], 'gi');
const user = await User.find({
$or: [{ name: pattern }, { skills: pattern }],
});
return user;
};
result = await ret();
}
if (result.length > 0) {
return res.json(sendResponse(httpStatus.OK, 'User found', result));
}
return res.json(sendResponse(httpStatus.NOT_FOUND, 'User not found'));
} catch (error) {
next(error);
}
};
Searching for PHP
correctly returns both users. However, searching for 'PHP Me' only returns:
{
"_id":"2",
"skills ["PHP", "Javascript"],
"name":"Me"
}
This is due to the issue that needs resolving. Please advise on how to address this problem.