Mongster

Guides

Indexes

Field-level and schema-level index definitions plus syncIndexes

Indexes in Mongster are declared next to the field or shape they protect. At sync time, Mongster walks every schema registered with the client, builds the full index list (including nested object and array paths), compares it against the indexes the database already has, and reconciles the difference: creating missing indexes and dropping stale ones.

Field-level helpers

Every primitive schema exposes the same index helpers. Each returns a new schema; they are immutable and safe to chain.

import {  } from "mongster";

const  = .({
  : .().(),
  : .().(),
  : .().({ : { : true } }),
  : .().(),
  : .().(),
  : .().(-1),
  : .().(3600),
});
HelperWhat it does
index(dir?)Plain index, default direction 1. Use -1 for descending.
uniqueIndex()unique: true on the same direction.
sparseIndex()sparse: true.
partialIndex(f)Adds a partialFilterExpression.
hashedIndex()Direction "hashed" for equality lookups.
textIndex()Direction "text" for full-text search.
ttl(seconds)TTL on a date field. Adds expireAfterSeconds. Alias: expires.

ttl(seconds) is only available on M.date().

Schema-level addIndex

Compound indexes that span multiple fields live on the schema instance. You can call addIndex multiple times.

import {  } from "mongster";

const  = .({
  : .(),
  : .(),
  : .(),
})
  .({ : 1, : -1 })
  .({ : 1, : -1 }, { : { : "open" } });

The same MongsterIndexOptions are accepted here as on field-level helpers that take options.

MongsterIndexOptions

Common options

You will reach for these most often.

interface CommonIndexOptions<Collection> {
  unique?: boolean;
  sparse?: boolean;
  partialFilterExpression?: Filter<Collection>;
  expireAfterSeconds?: number;
  name?: string;
}

Advanced options

These mirror MongoDB driver options for index creation. Reach for them only when the application data demands it.

interface AdvancedIndexOptions<Collection> {
  default_language?: string;
  weights?: Document;
  background?: boolean;
  storageEngine?: Document;
  commitQuorum?: number | string;
  version?: number;
  language_override?: string;
  textIndexVersion?: number;
  "2dsphereIndexVersion"?: number;
  bits?: number;
  min?: number;
  max?: number;
  bucketSize?: number;
  wildcardProjection?: Document;
  hidden?: boolean;
}

Embedded schemas carry their own indexes

Indexes declared on a nested M.object(...) are picked up with dot-notation paths so they end up on the top-level collection.

import {  } from "mongster";

const  = .({
  : .({
    : .().(),
  }),
});

Mongster will create { "profile.handle": 1 } with the unique option on the parent collection.

Sync indexes against the database

syncIndexes() compares the indexes collected from the schema against the indexes the database already has, creates the missing ones, and drops the ones that no longer match (unless you opt out).

const  = await .({ : true, : false });
OptionDefaultWhat it does
forcefalseReset the internal "synced" flag and re-run, even if syncIndexes was called once this process.
autoDroptrueDrop DB-side indexes that are not declared on the schema.

The return value is { created, dropped, unchanged }.

Error behavior

  • Model-level syncIndexes() re-throws as IndexSyncError on failure.
  • client.syncIndexes() swallows per-model errors via .catch(() => {}) so one failing model does not stop the rest of the sync.

Sync at connect time

If you want indexes to be applied the moment the client connects, turn on autoIndex: { syncOnConnect: true }.

await .("mongodb://127.0.0.1:27017/app", {
  : { : true },
});

autoIndex defaults to true. With that default on, model-level syncIndexes() runs the first time any write path is taken on the model — insertOne, insertMany, createOne, createMany, updateOne / updateMany / findOneAndUpdate / replaceOne / findOneAndReplace / upsertOne when upsert: true is passed, bulkWrite, plus the explicit User.syncIndexes() call. You can also call client.syncIndexes() directly to sync every model registered with that client.

[!WARNING] Keep autoIndex and syncIndexes usage under control on production. The recommended pattern is to run sync from a deploy step or admin script rather than every app boot, unless the collection is known to be small and stable.

On this page