0

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.

Amit Sharma
  • 668
  • 1
  • 6
  • 14
  • Does this answer your question https://stackoverflow.com/questions/9824010/mongoose-js-find-user-by-username-like-value – Subburaj Dec 30 '19 at 06:12
  • But then how to do multiple fields search like I want to search my search query 'al' in some fields (firstname, lastname, email). – Amit Sharma Dec 30 '19 at 06:15
  • check [here](https://jira.mongodb.org/browse/SERVER-15090) to learn about the new beta partial text search feature. – SuleymanSah Dec 30 '19 at 06:32

1 Answers1

1

You can use like this:

let searchText = "al";

let condition = { $or: [{ firstname: new RegExp("^" + searchText, "i") }, { lastname: new RegExp("^" + searchText, "i") }] }

const result = await User.find(contition).skip(1).limit(1);
Nikhil G
  • 2,096
  • 14
  • 18
  • It is working fine but in one case I am not getting results - like user firstname is 'alex' and if I search for 'le' than I got nothing. – Amit Sharma Dec 30 '19 at 07:08