Search code examples
mongodbloopbackjsstrongloop

Diacritic insensitive search on LoopbackJS


This question refers to: Diacritic Case-Insensitive search Loopback

I tried to add the following indexes - firstname and lastname of my NsUser model like @Markus_W_Mahlberg suggested - the loopback way.

    {
      "name": "NsUser",
      "base": "User",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "indexes": {
        "firstname": "text" ,
        "lastname": "text"
      },
      "properties": {
        "firstname": {
          "type": "string"
        },
       "lastname": {
          "type": "string"
        }
       …
     }
     …
    }

I also use an auto-update script in my server.js to make sure indexes are working like suggested here: https://github.com/strongloop/loopback-connector-mongodb/issues/103

My MongoDB shell version is: 3.2.3

Still it is not working. Any ideas?

EDIT: To answer to Pawan - When I display my Indexes in Mongo using:

> db.NsUser.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "needsporty_DB.NsUser"
    },
    {
        "v" : 1,
        "key" : {
            "text" : 1
        },
        "name" : "firstname",
        "ns" : "needsporty_DB.NsUser"
    },
    {
        "v" : 1,
        "key" : {
            "_fts" : "text",
            "_ftsx" : 1
        },
        "name" : "diatrics_insensitive_keys",
        "ns" : "needsporty_DB.NsUser",
        "weights" : {
            "firstname" : 1,
            "lastname" : 1
        },
        "default_language" : "english",
        "language_override" : "language",
        "textIndexVersion" : 3
    }
]

Solution

  • The Syntax of declaring index in model.json file is

    "indexes": {
         //A composite index two keys: key1 in ascending order and key2 in descending order
         "<indexName>": { "<key1>": 1, "<key2>" : -1 }
        //single field index
        "<indexName>": { "<key1>" : 1 }
       // for text indexes
       "<indexName>": { "<key1>" : "text" }   
    }
    

    check the docs

    So change your indexes object accordingly, As a collection can have at most one text index, so here you need to create a compound text index with firstname and lastname i.e

    "indexes": {
        "textSearchName" : { "firstname" : "text", "lastname" : "text" }
    }