Search code examples
databasemongodbmongoosenosql

Failed to search a substring in mongodb text search


I have implemented search functionality in my application where the user able to search across the database. So for that I have applied text index on one of the field named title. I am using the below query for searching:

let data = await reports.find({ active: true, $text: { $search: title } });

Let's say I have one report having title is "Random market" when user is entering full word "random", it's only fetching the data and if user is entering "ran" then its returning an empty array. How can I modify it to achieve desired functionality?


Solution

  • let regex = new RegExp(title, 'i'); // 'i' flag for case-insensitive matching
    let data = await reports.find({ active: true, title: { $regex: regex } });