Model Methods: Create Indexes

Creating multiple indexes in a collection.

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

This method has two parameters, the first is an { Array } with the indexes to be created defined in an 'array' if composed or in a 'string' with the name of the index to be created.


unique {Boolean}: Defines whether the indexes are unique;
direction {Number}: Specify index sorting direction;
locale {String}: Specifies the location in iso;
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.createIndexes(<query>, <options>);  
  • 15userModel
  • .createIndexes(
  • [
    16   'name',
    17   ['tags', 'city'],
    18],
  • {
  • 19  
  • unique:
  • false
  • ,
    20  
  • direction:
  • -
  • 1
  • ,
    21  
  • locale:
  • "pt-BR",  
    22
  • }
  • )
  • .then(
  • e =>
  • {
  • 23
    24   console
  • .log(
  • e
  • )
  • ;
    25  
  • //returns '3' indexes created successfully.
  • 26
  • }
  • )
  • .catch(
  • e =>
  • {
  • 27
    28   console
  • .log(
  • e
  • )
  • ;
    29  
  • //returns index 'X' already exists in your model.
  • 30
  • }
  • )
  • ;