Answer the question
In order to leave comments, you need to log in
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
}
});
const username = 'AlexPRO'; // То, что хочу найти
const findByUsername = await User.findOne({ username }); // Ищу по базе, но я ничего не нахожу, так как символы разных регистров
Answer the question
In order to leave comments, you need to log in
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,
}
});
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 questionAsk a Question
731 491 924 answers to any question