sumanth.js
sumanth.js

Reputation: 434

How to search the data from MongoDB database by concatenate the two data using nodejs

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

Answers (1)

sumanth.js
sumanth.js

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

Related Questions