Categories
JavaScript Answers

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

Spread the love

To find user by username LIKE value with Mongoose.js and JavaScript, we use the findOne method with a regex.

For instance, we write

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

to call findOne to find the document with field name like the 'Peter' by setting name to a regex with name in it.

We use the i flag to search in a case insensitive manner.

We get result from doc in the callback.

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 *