MongoDB命令行正则可用但Mongoose中失效问题求助
Let's walk through the issues in your code and get that search working properly:
1. The Critical Typo in Dot Escaping
First off, you mentioned in your note that you intended to replace . with \., but your code actually does the opposite—you're replacing . with \+:
// Wrong: turns . into + instead of escaping it word = word.replace(/\./g, '\\+')
This is a big problem because any . in your search term will get converted to +, completely breaking matches for terms that include dots, and messing up your regex logic overall. Fix this to properly escape dots:
// Correct: escapes . to \. for regex word = word.replace(/\./g, '\\.')
2. Verify Your Plus Sign Escaping
Your code for escaping + is actually correct:
word = word.replace(/\+/g, '\\+')
In JavaScript, when building a regex string to pass to MongoDB, we need to use two backslashes because the first one escapes the second in the string literal—so MongoDB receives the correct single backslash to escape the + regex special character.
3. (Optional) Make It More Robust
If you want to handle all regex special characters (not just + and .), use a generic regex escape function. This prevents future issues with characters like *, ?, ^, etc.:
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Then build your search term like this: let word = '^' + escapeRegExp(req.query.word);
Corrected Full Code
Here's the cleaned-up, fixed version of your code with error handling added too:
let word = '^' + req.query.word; // Escape + to \+ word = word.replace(/\+/g, '\\+'); // Fix the dot escaping typo word = word.replace(/\./g, '\\.'); // Or use the robust escape function instead of individual replaces: // const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // let word = '^' + escapeRegExp(req.query.word); Skill.find({ "name": { '$regex': word, '$options': 'i' } }) .limit(10) .exec(function (err, results) { if (err) { return res.status(500).json({ error: 'Failed to fetch skills: ' + err.message }); } res.json({ 'results': results }); });
When you search for C++ now, the processed word will be ^C\+\+, which matches exactly what you used successfully in the MongoDB shell. This should return the correct results instead of an empty array.
内容的提问来源于stack exchange,提问作者amulya349

