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.