Reputation: 434
I need to search the data from the MongoDB database by both first_name
and last_name
concatenate and also need to search phone
and email
separately. how to do that?
router.get("/:key", authenticate, async (req, res) => {
try {
let data = await SomeModel.find({
isActive: ACTIVE,
$or: [
{ first_name: { $regex: req.params.key, $options: "i" } },
{ last_name: { $regex: req.params.key, $options: "i" } },
{ phone: { $regex: req.params.key } },
{ email: { $regex: req.params.key, $options: "i" } },
],
});
return res.status(200).send(data);
} catch (err) {
return res.status(400).send(err.message);
}
});
Upvotes: 0
Views: 52
Reputation: 434
I tried this way and it works for me. reference
router.get("/:key", authenticate, async (req, res) => {
try {
let data = await SomeModel.find({
isActive: ACTIVE,
$or: [
{
$expr: {
$regexMatch: {
input: {
$concat: [`$first_name`, " ", `$last_name`],
},
regex: req.params.key,
options: "i",
},
},
},
{ phone: { $regex: req.params.key } },
{ email: { $regex: req.params.key, $options: "i" } },
],
});
return res.status(200).send(data);
} catch (err) {
return res.status(400).send(err.message);
}
});
Upvotes: 0