Hbib Bekir
Hbib Bekir

Reputation: 11

Fuzzy search with mongoDB nestjs

Obviously using typescript cause of nest so using the plugin 'mongoose-fuzzy-searching' is not supported so im trying to use the aggregate method but its not working so far (always returning empty result), if anyone knows an alternative or has the answer to the problem please I need help.

this is the code

  async get(page: any, query: any) {
    const offset = (page - 1) * 8;

    let students = await this.studentModel
      .aggregate()
      .search({
        text: {
          query: query,
          path: 'fullName',
          fuzzy: {
            maxEdits: 2,
          },
        },
      })
      .skip(offset)
      .limit(8);

    let count = await this.studentModel.countDocuments(query);

    return { items: students, count: count };
  }

Upvotes: 0

Views: 1184

Answers (1)

Hbib Bekir
Hbib Bekir

Reputation: 11

Ok I found an alternative solution with the help of this post so I decided to write it down here for anyone looking into this problem, using the find method, I passed a regex (regular expression) as follows:

function escapeRegex(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
const regex = new RegExp(escapeRegex(search), 'gi');

let students = await this.studentModel.find({ fullName: { $regex: regex } })

Upvotes: 1

Related Questions