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

Time:10-27

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,
        });
      }
    });
};

CodePudding user response:

You can use $and operator to join two queries.

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