有人有想法吗,我该如何修改这段代码以便可以根据标题或评分或两者都进行搜索?我已经尝试了几种方法,包括使用$and运算符,但都没有成功
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粉9868609502023-09-12 14:14:58
如果您想要根据名称或评分进行搜索,或者同时使用两者,您可以简单地使用下面的查询。您不需要使用$eq运算符与rated的过滤器一起使用。mongoose的find函数会直接匹配值,而不使用$eq运算符。
if (filters?.title) { query.title = { $regex: `^${filters.title.replace(/[-[\]{}()*+?.,\/^$|#\s]/g, "\$&")}`, $options: "i" } } if (filters?.rated) { query.rated = filters.rated } console.log(query)