My User model schema is
const userSchema = new mongoose.Schema(
{
firstname: {
type: String,
required: true,
trim: true
},
lastname: {
type: String,
trim: true
},
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true
},
password: {
type: String
},
phone: {
type: Number,
trim: true,
unique: true,
sparse: true
}
});
And I have made an index for text search in multiple fields(firstname, lastname, email)
userSchema.index({firstname: 'text', lastname: 'text', email: 'text'}, {default_language: 'none'});
Now I am searching 'alex' in users -
const result = await User.find({$text : { $search: 'alex' }}).skip(1).limit(1);
I got my result when I search for the whole word like 'alex' but if I search for 'al' then I got nothing.
So I want to get the result when I search for a partial word like 'al' then I got 'alex' record in results too.
As someone suggested to use this
let searchText = "l";
let condition = { $or: [{ firstname: new RegExp("^" + searchText, "i") }, { lastname: new RegExp("^" + searchText, "i") }] }
const result = await User.find(condition);
It is working fine but still not cover one case like I have a document with firstname - 'alex' and if I search for 'le' than I should also get this document.