Registry / database / mongodb-index-model

mongodb-index-model

JSON →
library4.1.2jsnpmunverified

A utility library for parsing, validating, and formatting MongoDB index specifications. Version 4.1.2 provides a structured model to work with MongoDB index definitions, including index keys, options (like unique, sparse, TTL), and collation. It validates index definitions and provides helpers to convert between different representations (e.g., from shell syntax to driver objects). This package is part of the MongoDB Compass project, updated alongside Compass releases, with a stable API focused on internal use. It differentiates from direct driver use by offering higher-level validation and normalization of index specs, making it useful for tools and UIs that manage MongoDB indexes. ESM-only since v4; TypeScript types are bundled.

npm install mongodb-index-model
INSTALL
IMPORT
SIG · MONGODB-INDEX-MODE
M
mongodb-index-model
databasejavascriptv4.1.2
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

default
import IndexModel from 'mongodb-index-model'
const IndexModel = require('mongodb-index-model')
ESM-only since v4; CommonJS require will fail with ERR_REQUIRE_ESM.
IndexModel
import IndexModel from 'mongodb-index-model'
Default export is the IndexModel class. In TypeScript, typeof IndexModel provides types.
types
import type { IndexDefinition } from 'mongodb-index-model'
TypeScript types are exported alongside the main export for type assertions.

Creates an IndexModel, validates the index spec, and converts it to driver and shell formats.

import IndexModel from 'mongodb-index-model'; const indexSpec = { key: { name: 1, age: -1 }, unique: true, name: 'name_age_unique' }; const model = new IndexModel(indexSpec); // Validate the index definition const validation = model.validate(); if (!validation.isValid) { console.error('Invalid index:', validation.errors); } else { console.log('Index definition is valid'); } // Get the normalized driver option form const driverIndex = model.toDriver(); console.log('Driver index:', driverIndex); // Get the shell-compatible form const shellIndex = model.toShell(); console.log('Shell index:', shellIndex); // Check index type (single, compound, text, etc.) console.log('Index type:', model.type);
Debug
Known issues
breakingVersion 4.0 dropped CommonJS support; the package is ESM-only. Node.js 14+ required.
fix
Switch to ES modules: update package.json type to "module" or use .mjs extension.
affects: >=4.0.0
deprecatedThe `validate` method returns a validation object; the old `isValid` property has been removed.
fix
Call `model.validate().isValid` instead of accessing `model.isValid` directly.
affects: >=3.0.0
gotchaThe constructor accepts a plain object, but does not mutate the original object; it creates a deep clone internally via lodash.
fix
Ensure to capture the returned model; modifications to the original indexSpec object will not affect the model after creation.
affects: >=1.0.0
gotchaIndex keys must be provided as an object with key names and direction (1 or -1); nested keys like { 'a.b': 1 } are allowed but not validated for path existence.
fix
Double-check key paths and directions manually; the model does not connect to MongoDB to verify fields.
affects: >=1.0.0
deprecatedThe `toJSON` method is deprecated; use `toShell` or `toDriver` for specific output formats.
fix
Replace `model.toJSON()` with `model.toShell()` for human-readable output, or with `model.toDriver()` for driver options.
affects: >=2.0.0
gotchaIndex names: if not provided, the model generates a name from the key pattern; this may differ from MongoDB's automatic naming in some cases, especially for text indexes.
fix
Always provide an explicit `name` property to avoid unexpected index names when creating indexes via driver.
affects: >=1.0.0
Errors
Common errors & fixes
ERR_REQUIRE_ESM: require() of ES Module /path/to/node_modules/mongodb-index-model/index.js from /path/to/file.js not supported.
The package is ESM-only since v4, but the consuming code uses require() for CommonJS.
fix
Convert the consuming file to ES module (use import instead of require) or downgrade to mongodb-index-model@3.x.
TypeError: IndexModel is not a constructor
Importing the module incorrectly; e.g., using a named import like { IndexModel } instead of default import.
fix
Use `import IndexModel from 'mongodb-index-model'` (default import).
ValidationError: key must be an object with field names and directions (1/-1)
The `key` property in the index spec is missing, malformed, or uses incorrect direction values.
fix
Ensure `key` is an object like { field1: 1, field2: -1 }. Directions must be numeric 1 (ascending) or -1 (descending).
TypeError: Cannot read properties of undefined (reading 'validate')
The model was not instantiated correctly; perhaps forgot 'new' keyword.
fix
Use `new IndexModel(...)` to create an instance.
Upgrade
Version history
4.1.2latest on npm
Audit
Dependencies
mongodb-connection-string-urloptionalUsed for parsing and handling MongoDB connection strings, which may include index-related options.
lodashrequiredProvides utility functions for deep cloning, merging, and comparing index definitions.
Agent activity
2 hits · last 30 days
node
2
Resources