Query mongodb with two parameters
P粉665679053
P粉665679053 2023-09-11 19:07:07
0
1
623

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粉665679053
P粉665679053

reply all(1)
P粉986860950

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template