Categories
JavaScript Answers

How to find user by username LIKE value with Mongoose.js?

Spread the love

Sometimes, we want to find user by username LIKE value with Mongoose.js.

In this article, we’ll look at how to find user by username LIKE value with Mongoose.js.

How to find user by username LIKE value with Mongoose.js?

To find user by username LIKE value with Mongoose.js, we can use findOne with a regex.

For instance, we write

const name = 'Peter';

model.findOne({
  name: new RegExp(`^${name}$`, "i")
}, (err, doc) => {
  //...
});

to call model.findOne with an object that searches the name field with a regex.

We set name to a regex that matches anything that has name in the string.

And we add the 'i' flag to the regex to search in a case-insensitive manner.

As a result, any entry with name having 'Peter' anywhere in the string would be matched.

Conclusion

To find user by username LIKE value with Mongoose.js, we can use findOne with a regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *