CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mongoose

Mongoose is a comprehensive MongoDB object modeling tool designed for asynchronous environments with schema-based validation, query building, and business logic hooks.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

connection.mddocs/

Connection Management

Database connection establishment, management, and configuration with support for multiple connections, automatic reconnection, and connection pooling.

Capabilities

Connection Establishment

Connect to MongoDB databases with comprehensive configuration options and automatic reconnection handling.

/**
 * Creates a connection to a MongoDB database
 * @param uri - MongoDB connection string
 * @param options - Connection configuration options
 * @returns Promise resolving to mongoose instance
 */
mongoose.connect(uri: string, options?: ConnectOptions): Promise<typeof mongoose>;

/**
 * Creates a new connection instance (for multiple database connections)
 * @param uri - MongoDB connection string  
 * @param options - Connection configuration options
 * @returns New connection instance
 */
mongoose.createConnection(uri: string, options?: ConnectOptions): Connection;

/**
 * Closes all connections
 * @returns Promise that resolves when all connections are closed
 */
mongoose.disconnect(): Promise<void>;

Usage Examples:

// Basic connection
await mongoose.connect('mongodb://localhost:27017/myapp');

// Connection with options
await mongoose.connect('mongodb://localhost:27017/myapp', {
  maxPoolSize: 10,
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
  bufferCommands: false,
  bufferMaxEntries: 0
});

// Multiple connections
const conn1 = mongoose.createConnection('mongodb://localhost:27017/app1');
const conn2 = mongoose.createConnection('mongodb://localhost:27017/app2');

// Using connection-specific models
const User = conn1.model('User', userSchema);
const Product = conn2.model('Product', productSchema);

Connection Object

The Connection class represents a connection to MongoDB with properties and methods for managing the connection state.

interface Connection extends EventEmitter {
  /** Current connection state (0=disconnected, 1=connected, 2=connecting, 3=disconnecting) */
  readyState: number;
  
  /** Native MongoDB database object */
  db: mongodb.Db;
  
  /** Database name */
  name: string;
  
  /** Connection host */
  host: string;
  
  /** Connection port */
  port: number;
  
  /** Models registered on this connection */
  models: { [key: string]: Model<any> };
  
  /** Native MongoDB collections */
  collections: { [key: string]: mongodb.Collection };
  
  /** Connection configuration */
  config: any;
  
  /** Client instance */
  client: mongodb.MongoClient;
  
  /** Array of plugins applied to this connection */
  plugins: Array<any>;
  
  /** Connection identifier for debugging */
  id: number;
  
  /** Username from connection URI */
  user: string;
  
  /** Password from connection URI */
  pass: string;
}

Connection Methods

Methods available on Connection instances for database and collection operations.

interface Connection {
  /**
   * Closes the connection
   * @param force - Force close without waiting for operations to complete  
   * @returns Promise that resolves when connection is closed
   */
  close(force?: boolean): Promise<void>;
  
  /**
   * Defines a model on this connection
   * @param name - Model name
   * @param schema - Schema definition
   * @param collection - Collection name (optional)
   * @returns Model constructor
   */
  model<T>(name: string, schema?: Schema<T>, collection?: string): Model<T>;
  
  /**
   * Removes a model from this connection
   * @param name - Model name to remove
   * @returns this connection
   */
  deleteModel(name: string): this;
  
  /**
   * Gets native collection object
   * @param name - Collection name
   * @returns Native MongoDB collection
   */
  collection(name: string): mongodb.Collection;
  
  /**
   * Drops the database
   * @returns Promise that resolves when database is dropped
   */
  dropDatabase(): Promise<void>;
  
  /**
   * Drops a specific collection
   * @param collection - Collection name to drop
   * @returns Promise that resolves when collection is dropped
   */
  dropCollection(collection: string): Promise<boolean>;
  
  /**
   * Synchronizes indexes for all models on this connection
   * @returns Promise that resolves when indexes are synced
   */
  syncIndexes(): Promise<void>;
  
  /**
   * Starts a new session for transactions
   * @param options - Session options
   * @returns ClientSession for transaction operations
   */
  startSession(options?: mongodb.SessionOptions): Promise<mongodb.ClientSession>;
  
  /**
   * Executes function within a transaction
   * @param fn - Function to execute in transaction
   * @param options - Transaction options
   * @returns Promise with transaction result
   */
  transaction<T>(fn: (session: mongodb.ClientSession) => Promise<T>, options?: any): Promise<T>;
  
  /**
   * Creates a change stream on the database
   * @param pipeline - Aggregation pipeline for filtering changes
   * @param options - Change stream options
   * @returns Change stream cursor
   */
  watch(pipeline?: any[], options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream;
  
  /**
   * Switch to a different database using the same connection
   * @param name - Database name
   * @returns New connection to the specified database
   */
  useDb(name: string): Connection;
  
  /**
   * Returns promise that resolves when connection is established
   * @returns Promise resolving when connected
   */
  asPromise(): Promise<this>;
  
  /**
   * Perform cross-collection bulk operations
   * @returns Bulk operation builder
   */
  bulkWrite<TSchemaMap>(): any;
  
  /**
   * Closes and destroys connection permanently
   * @param force - Force destruction without waiting
   * @returns Promise that resolves when destroyed
   */
  destroy(force?: boolean): Promise<void>;
  
  /**
   * Create collections for all registered models
   * @param continueOnError - Continue creating collections if one fails
   * @returns Promise that resolves when collections are created
   */
  createCollections(continueOnError?: boolean): Promise<void>;
  
  /**
   * List all collections in the database
   * @returns Promise with array of collection information
   */
  listCollections(): Promise<CollectionInfo[]>;
  
  /**
   * List all databases accessible by this connection
   * @returns Promise with database list information
   */
  listDatabases(): Promise<ListDatabasesResult>;
  
  /**
   * Set MongoDB client instance for this connection
   * @param client - MongoDB client instance
   * @returns this connection
   */
  setClient(client: mongodb.MongoClient): this;
  
  /**
   * Execute operation within a session context
   * @param executor - Function to execute with session
   * @returns Promise with operation result
   */
  withSession<T>(executor: (session: mongodb.ClientSession) => Promise<T>): Promise<T>;
}

Connection Events

Connections emit events for monitoring connection state changes and handling errors.

// Connection events
connection.on('connected', () => {});      // Successfully connected
connection.on('error', (err) => {});       // Connection error occurred
connection.on('disconnected', () => {});   // Connection lost
connection.on('reconnected', () => {});    // Successfully reconnected
connection.on('close', () => {});          // Connection closed
connection.on('fullsetup', () => {});      // All replica set members connected
connection.on('all', () => {});            // All replica set members connected
connection.on('reconnectFailed', () => {}); // Reconnection failed

Usage Examples:

const connection = mongoose.createConnection('mongodb://localhost:27017/myapp');

// Handle connection events
connection.on('connected', () => {
  console.log('Connected to MongoDB');
});

connection.on('error', (err) => {
  console.error('Connection error:', err);
});

connection.on('disconnected', () => {
  console.log('Disconnected from MongoDB');
});

// Check connection state
if (connection.readyState === 1) {
  console.log('Connection is active');
}

// Use native database operations
const db = connection.db;
const result = await db.collection('users').findOne({ name: 'John' });

Default Connection

Mongoose provides a default connection accessible through the main mongoose object.

/** Default connection instance */
mongoose.connection: Connection;

/** Connection state constants */
mongoose.STATES: {
  disconnected: 0;
  connected: 1;
  connecting: 2;
  disconnecting: 3;
  uninitialized: 99;
};

Usage Examples:

// Access default connection
const defaultConnection = mongoose.connection;

// Monitor default connection
mongoose.connection.on('connected', () => {
  console.log('Default connection established');
});

// Check if connected
if (mongoose.connection.readyState === mongoose.STATES.connected) {
  console.log('Ready to perform operations');
}

Types

interface ConnectOptions {
  /** Use new URL parser */
  useNewUrlParser?: boolean;
  
  /** Use unified topology */
  useUnifiedTopology?: boolean;
  
  /** Buffer commands when not connected */
  bufferCommands?: boolean;
  
  /** Max number of buffered commands */
  bufferMaxEntries?: number;
  
  /** Auto-create collections */  
  autoCreate?: boolean;
  
  /** Auto-create indexes */
  autoIndex?: boolean;
  
  /** Maximum connection pool size */
  maxPoolSize?: number;
  
  /** Minimum connection pool size */
  minPoolSize?: number;
  
  /** Max idle time for pooled connections (ms) */
  maxIdleTimeMS?: number;
  
  /** Server selection timeout (ms) */
  serverSelectionTimeoutMS?: number;
  
  /** Socket timeout (ms) */
  socketTimeoutMS?: number;
  
  /** IP family (4 or 6) */
  family?: number;
  
  /** Authentication database */
  authSource?: string;
  
  /** Username for authentication */
  user?: string;
  
  /** Password for authentication */
  pass?: string;
  
  /** Database name */
  dbName?: string;
  
  /** Write concern */
  w?: string | number;
  
  /** Write concern timeout */
  wtimeout?: number;
  
  /** Journal write concern */
  j?: boolean;
  
  /** Read preference */
  readPreference?: string;
  
  /** Read preference tags */
  readPreferenceTags?: any[];
  
  /** Replica set name */
  replicaSet?: string;
  
  /** SSL options */
  ssl?: boolean;
  sslValidate?: boolean;
  sslCA?: string | string[] | Buffer | Buffer[];
  sslCert?: string | Buffer;
  sslKey?: string | Buffer;
  sslPass?: string;
  
  /** Additional MongoDB driver options */
  [key: string]: any;
}

interface CollectionInfo {
  /** Collection name */
  name: string;
  
  /** Collection type */
  type: string;
  
  /** Collection options */
  options: any;
  
  /** Collection info */
  info: any;
  
  /** Collection UUID */
  idIndex: any;
}

interface ListDatabasesResult {
  /** Array of database information */
  databases: Array<{
    /** Database name */
    name: string;
    
    /** Database size in bytes */
    sizeOnDisk: number;
    
    /** Whether database is empty */
    empty: boolean;
  }>;
  
  /** Total size of all databases */
  totalSize: number;
}

docs

aggregation.md

connection.md

document.md

errors.md

index.md

model.md

query.md

schema.md

utilities.md

tile.json