Model Methods: Create Index

Creating indexes in a collection.

🪶 The createIndex
  • method is used to create indexes in a collection.

    This method has two parameters, the first is a { Array|String } with the index or composite indexes to be created.


    unique {Boolean}: Defines whether the indexes are unique;
    direction {Number}: Specify index sorting direction;
    locale {String}: Specifies the location in iso;
    name {String}: Defines the name of the composite index.
    1
  • import
  • MerlinDB,
  • {
  • Schema
  • }
  • from
  • "@chrisaxxwell/merlin-db";
    2
  • //Or if you are using 'merlindb.max.js' just call 'new MerlinDB()';
  • 3
    4
  • const
  • merlin =
  • new
  • MerlinDB(
  • )
  • ;
    5merlin
  • .connect(
  • "USER-DATABASE"
  • )
  • ;
    6
    7
  • const
  • UserSchema =
  • Schema(
  • {
  •   
    8  
  • name:
  • String
  • ,
    9  
  • age:
  • Number
  • 10
  • }
  • )
  • ;
    11
    12
  • var
  • userModel = merlin
  • .model(
  • "User", UserSchema
  • )
  • ;
    13
    14
  • //userModel.createIndex(<query>, <options>);  
  • 15userModel
  • .createIndex(
  • ['tags', 'city'],
  • {
  • 16  
  • unique:
  • false
  • ,
    17  
  • direction:
  • -
  • 1
  • ,
    18  
  • locale:
  • "pt-BR",
    19  
  • name:
  • "tags-e-city"
    20  
  • //If false, it creates this way tags_city
  • 21
  • }
  • )
  • .then(
  • e =>
  • {
  • 22
    23   console
  • .log(
  • e
  • )
  • ;
    24  
  • //returns: Index created!.
  • 25
  • }
  • )
  • .catch(
  • e =>
  • {
  • 26
    27   console
  • .log(
  • e
  • )
  • ;
    28  
  • //returns index 'X' already exists in your model.
  • 29
  • }
  • )
  • ;