有人有想法嗎,我該如何修改這段程式碼以便可以根據標題或評分或兩者都進行搜尋?我已經嘗試了幾種方法,包括使用$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)