search

Home  >  Q&A  >  body text

Query mongodb with two parameters

Does anyone have an idea how I could modify this code so that I can search based on title or rating or both? I've tried several approaches, including using the $and operator, with no success

static async getMovies({
    filters = null,
    page = 0,
    moviesPerPage = 20,
  } = {}) {
    let query = {}
    if (filters) {
      if ("title" in filters) {
        console.log(filters["title"]);
        query.title = { $regex: filters["title"], $options: "i" };
      }  if ("rated" in filters) {
        query.rated = { $eq: filters["rated"] };
      }
    }

    let cursor
    try {
      cursor = await movies.find(query)
        .limit(moviesPerPage)
        .skip(moviesPerPage * page);
      const moviesList = await cursor.toArray();

      for (let i = 0; i < moviesList.length; i++) {
        const movie = moviesList[i];
        const movieReviews = await reviews
          .find({ movie_id: movie._id })
          .toArray();
        movie.review = movieReviews;
      }

      const totalNumMovies = await movies.countDocuments(query);
      return { moviesList, totalNumMovies };
    } catch (e) {
      console.error(`无法发出查找命令,${e}`);
      return { moviesList: ["error"], totalNumMovies: 0 };
    }
  }
P粉665679053P粉665679053531 days ago664

reply all(1)I'll reply

  • P粉986860950

    P粉9868609502023-09-12 14:14:58

    If you want to search based on name or rating, or both, you can simply use the query below. You don't need to use the $eq operator with rated filters. Mongoose's find function will match the value directly without using the $eq operator.

    if (filters?.title) {
      query.title = { $regex: `^${filters.title.replace(/[-[\]{}()*+?.,\/^$|#\s]/g, "\$&")}`, $options: "i" }
    }  
    if (filters?.rated) {
      query.rated = filters.rated
    }
    console.log(query)

    reply
    0
  • Cancelreply