Mongoose:Angular应用中如何实现多字段部分匹配的$or查询
Got it, let's sort out this query issue for you. The problem with your current code is that when you write /filter/ in the Mongoose query, you're creating a regex that matches the literal string "filter" instead of using the value of your filter variable. That's why it works in the MongoDB shell (where you hardcode /Su/) but not when you try to use the dynamic parameter from your API.
The Correct Approach: Use RegExp for Dynamic Regex
To create a regex that uses your filter variable's value, you need to use the JavaScript RegExp constructor instead of regex literal syntax. Here's how to update your code:
exports.listPartialMatches = function(req, res) { const filter = req.params.filter; // Create a regex from the filter parameter (add 'i' flag for case-insensitive matching if needed) const searchRegex = new RegExp(filter, 'i'); Col.find({ $or: [ { product: searchRegex }, { location: searchRegex }, { category: searchRegex }, { owner: searchRegex } ] }) .then(results => { res.status(200).json(results); }) .catch(error => { res.status(500).json({ message: 'Error fetching matches', error: error.message }); }); };
Key Details:
- The
RegExpconstructor lets you pass your dynamicfiltervalue as the first argument. - The second argument (
'i') enables case-insensitive matching—remove it if you want exact case matching. - You can either use
Col.find({ $or: [...] })directly (like in the shell) or chain.or([...])afterCol.find()—both work the same way, so pick whichever style you prefer.
Why Your Original Code Didn't Work
When you write /filter/ in JavaScript, it's a regex literal that looks for the exact string "filter" in your document fields. Since you want to match the value of the filter variable (like "Su" from your shell example), you need to construct the regex dynamically with RegExp.
内容的提问来源于stack exchange,提问作者Code2Code

