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

xj3cbfub  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(159)

我只想知道如何在1 Note.find( )内连接这两个查询

  • 第一部分:Note.find({ creator: id })
  • 第二部分:Note.find({ $or: [{ tags: { $regex: req.params.key } }],})

整个代码块:

  1. exports.searchUserNotes = (req, res) => {
  2. const id = req.userId;
  3. Note.find({ creator: id })
  4. .then(
  5. Note.find({
  6. $or: [{ tags: { $regex: req.params.key } }],
  7. })
  8. )
  9. .then((data) => {
  10. if (data.length === 0) {
  11. res.status(404).json({
  12. Error: `No notes with the '${req.params.key}' tag were found.`,
  13. });
  14. } else {
  15. res.status(200).json({
  16. Success: `${data.length} notes with the '${req.params.key}' tag were found.`,
  17. data,
  18. });
  19. }
  20. });
  21. };
aoyhnmkz

aoyhnmkz1#

您可以使用$and运算符联接两个查询。

  1. Note.find({
  2. $and: [
  3. { creator: id },
  4. { $or: [{ tags: { $regex: req.params.key } }] }
  5. ]
  6. })

相关问题