D
D
dotajax2018-01-16 21:13:15
JavaScript
dotajax, 2018-01-16 21:13:15

How to do case-insensitive searches in MongoDB through Mongoose?

I'm getting started with Mongo. I'm doing a username busy check in my form.
There is a model:

const UserSchema = Schema({
  username: {
    type: String,
    required: 'Username is not specified'
    trim: true
  }
});

The username field accepts a string of different case, I need to arrange a name search (username) in the database in full compliance without case strictness , for example like this:
There is a user in the database named AlexPro , I'm looking for him by name:
const username = 'AlexPRO'; // То, что хочу найти
const findByUsername = await User.findOne({ username }); // Ищу по базе, но я ничего не нахожу, так как символы разных регистров

How to ignore case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Batukhtin, 2018-01-16
@0lorin

You can regularly:
But then it will not use the index (which, by the way, must be added).
A In general, in such cases, usually result in lowercase when saving.

const UserSchema = Schema({
  username: {
    type: String,
    required: 'Username is not specified',
    trim: true,

    index: true,
    lowercase: true,
  }
});

D
dotajax, 2018-01-17
@dotajax

In general, I came to this decision:

const username = 'AlexPRO';

// если число, то преобразую в строку (чтобы не было ошибки с toLowerCase)
if (isNaN(username)) {
  // ...
}

// ищем логин с полной точностью, за исключением регистра
const user = await User.findOne({ username: new RexExp('^' + username + '$', 'i') });

if (findByUsername.length) {
  // ... response OK (200)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question