Finding words from two properties in a mongodb document

Viewed 155

I want to find a word from two properties (columns) 'firstname' and 'lastname' from a document. The code below is not giving the response while finding from multiple properties. I am new to mongo db please make me aware of my mistake and its possible solution.

router.get('/search/:user', (req, res) => {
  const searchField = new RegExp(req.params.user, 'i');
  User.find({ firstname: { $regex: searchField }, lastname: { $regex: searchField } })
    .then((data) => {
      res.json(data);
    })
    .catch((error) => {
      console.log(error);
    });
});

It is working when I pass a single property though. How can I make it possible to find from both 'firstname' and 'lastname' at once.

1 Answers

Rohit Dalal's answer is the correct solution.

User.find({ $or: [{ firstname: { $regex: searchField } }, { lastname: { $regex: searchField } }] })

This is the desired solution.

Related