Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I join a search parameter with $regex and $or in mongoose? (mongoDB, NodeJS)

I just want to know how to join these two queries inside only 1 Note.find( )

  • first part: Note.find({ creator: id })
  • Second part: Note.find({ $or: [{ tags: { $regex: req.params.key } }],})

The whole code block:

exports.searchUserNotes = (req, res) => {
  const id = req.userId;
  Note.find({ creator: id })
    .then(
      Note.find({
        $or: [{ tags: { $regex: req.params.key } }],
      })
    )
    .then((data) => {
      if (data.length === 0) {
        res.status(404).json({
          Error: `No notes with the '${req.params.key}' tag were found.`,
        });
      } else {
        res.status(200).json({
          Success: `${data.length} notes with the '${req.params.key}' tag were found.`,
          data,
        });
      }
    });
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use $and operator to join two queries.

Note.find({
  $and: [
    { creator: id },
    { $or: [{ tags: { $regex: req.params.key } }] }
  ]
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading