`find()` with LIKE in Mongoose

Jun 5, 2020

The SQL LIKE operator lets you search for strings with wildcards. MongoDB doesn't have a similar operator - the $text operator performs a more sophisticated text search. But MongoDB does support regular expression queries that work similarly to LIKE.

For example, suppose you want to find all users whose email contains gmail. You can simply search by the JavaScript regular expression /gmail/:

const User = mongoose.model('User', mongoose.Schema({
  email: String
}));

await User.create([
  { email: 'sergei@google.com' },
  { email: 'bill@microsoft.com' },
  { email: 'test@gmail.com' },
  { email: 'gmail@google.com' }
]);

const docs = await User.find({ email: /gmail/ });
docs.length; // 2
docs.map(doc => doc.email).sort(); // ['gmail@google.com', 'test@gmail.com']

Equivalently, you can use the $regex operator.

const docs = await User.find({ email: { $regex: 'gmail' } });

Note that Mongoose does not escape special characters in regexps for you. If you want to use $regexp with user entered data, you should sanitize the string first using escape-string-regexp or a similar library for escaping regular expression special characters.

const escapeStringRegexp = require('escape-string-regexp');
const User = mongoose.model('User', mongoose.Schema({
  email: String
}));

await User.create([
  { email: 'sergey@google.com' },
  { email: 'bill@microsoft.com' },
  { email: 'test+foo@gmail.com' }
]);

const $regex = escapeStringRegexp('+foo');
const docs = await User.find({ email: { $regex } });

docs.length; // 1
docs[0].email; // 'test+foo@gmail.com'

// Throws: MongoError: Regular expression is invalid: nothing to repeat
await User.find({ email: { $regex: '+foo' } });

Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mongoose Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!