Mongoose Like操作符问题:下述代码返回空数组,问题出在哪?
Hey there! Let's break down why your current code isn't working and how to fix it quickly.
The Root Problem
Right now, you're passing a string '/' + search + '/' to the firstName field in your find() query. Mongoose interprets this as an exact string match—meaning it's only looking for documents where firstName is literally equal to that string with slashes around it (like "/John/" instead of just "John"). That's why you're getting an empty array back—your database almost certainly doesn't have documents with that exact formatted string in the firstName field.
The Fix: Use Actual Regular Expressions
To perform a fuzzy search (matching any firstName that contains your search term), you need to pass a RegExp object to Mongoose, not a string. Here are two reliable ways to do this:
1. Dynamic Regular Expression (Best for Variable Search Terms)
Since your search parameter is dynamic, use the RegExp constructor to create a regex on the fly:
const user = mongoose.model('user', { firstName: String }); async function usersBySearch(search) { // Basic case-sensitive match return await user.find({ firstName: new RegExp(search) }); }
If you want case-insensitive matching (so "john", "John", and "JOHN" all get matched), add the 'i' flag:
async function usersBySearch(search) { return await user.find({ firstName: new RegExp(search, 'i') }); }
2. Literal Regex (Only for Fixed Search Terms)
If your search term was hardcoded (not a variable), you could use a regex literal directly—but this won't work with dynamic search values:
// Only works if you know the search term upfront return await user.find({ firstName: /John/ });
Bonus: Performance Tip
If you're working with a large dataset, consider adding an index to the firstName field to speed up regex queries. For case-insensitive or partial matches, a text index might be even more efficient:
// Add this when defining your schema (instead of the simple object you're using now) const userSchema = new mongoose.Schema({ firstName: { type: String, index: true } }); const user = mongoose.model('user', userSchema);
内容的提问来源于stack exchange,提问作者Raj Chaudhary

