Mongoose is a comprehensive MongoDB object modeling tool designed for asynchronous environments with schema-based validation, query building, and business logic hooks.
npx @tessl/cli install tessl/npm-mongoose@8.18.0Mongoose is a comprehensive MongoDB Object Document Mapper (ODM) for Node.js that provides a schema-based solution for modeling application data. It includes built-in type casting, validation, query building, business logic hooks, and more, designed for asynchronous environments.
npm install mongooseconst mongoose = require('mongoose');ES6/TypeScript:
import mongoose from 'mongoose';
// Or with named imports
import { Schema, model, connect } from 'mongoose';const mongoose = require('mongoose');
// Connect to MongoDB
await mongoose.connect('mongodb://localhost:27017/myapp');
// Define a schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 0 },
createdAt: { type: Date, default: Date.now }
});
// Create a model
const User = mongoose.model('User', userSchema);
// Create and save a document
const user = new User({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
await user.save();
// Query documents
const users = await User.find({ age: { $gte: 18 } });Mongoose is built around several key components:
Database connection establishment, management, and configuration with support for multiple connections and automatic reconnection.
// Static methods
mongoose.connect(uri: string, options?: ConnectOptions): Promise<typeof mongoose>;
mongoose.createConnection(uri: string, options?: ConnectOptions): Connection;
mongoose.disconnect(): Promise<void>;
// Connection events and properties
interface Connection {
readyState: number;
db: mongodb.Db;
models: { [key: string]: Model<any> };
}Define document structure, validation rules, indexes, virtual properties, and middleware with a rich schema type system.
class Schema<T = any> {
constructor(definition?: SchemaDefinition<T>, options?: SchemaOptions);
add(obj: SchemaDefinition<T>, prefix?: string): this;
path(path: string): SchemaType | undefined;
virtual(name: string): VirtualType;
index(fields: any, options?: any): this;
pre(method: string, fn: Function): this;
post(method: string, fn: Function): this;
method(name: string, fn: Function): this;
static(name: string, fn: Function): this;
}
// Built-in schema types
Schema.Types.String, Schema.Types.Number, Schema.Types.Date,
Schema.Types.Boolean, Schema.Types.ObjectId, Schema.Types.Array,
Schema.Types.Mixed, Schema.Types.Decimal128, Schema.Types.Map,
Schema.Types.UUID, Schema.Types.BigIntModel class providing static methods for CRUD operations, queries, aggregation, and document management with full MongoDB feature support.
interface Model<T> {
// Document creation
static create<T>(doc: T): Promise<T>;
static insertMany<T>(docs: T[]): Promise<T[]>;
// Queries
static find<T>(filter: FilterQuery<T>): Query<T[], T>;
static findOne<T>(filter: FilterQuery<T>): Query<T | null, T>;
static findById<T>(id: any): Query<T | null, T>;
// Updates
static updateOne<T>(filter: FilterQuery<T>, update: UpdateQuery<T>): Query<UpdateResult, T>;
static findOneAndUpdate<T>(filter: FilterQuery<T>, update: UpdateQuery<T>): Query<T | null, T>;
// Deletions
static deleteOne<T>(filter: FilterQuery<T>): Query<DeleteResult, T>;
static findOneAndDelete<T>(filter: FilterQuery<T>): Query<T | null, T>;
}Document instance methods for saving, validation, field access, and lifecycle management with change tracking and middleware.
interface Document {
save(): Promise<this>;
validate(): Promise<void>;
set(path: string, val: any): this;
get(path: string): any;
markModified(path: string): void;
toObject(options?: ToObjectOptions): any;
toJSON(options?: ToObjectOptions): any;
isModified(path?: string): boolean;
isNew: boolean;
id: string;
_id: ObjectId;
}Fluent query builder with method chaining, population, lean queries, and advanced MongoDB query operations.
interface Query<ResultType, DocType> {
// Query conditions
where(path: string, val?: any): this;
equals(value: any): this;
gt(value: any): this;
gte(value: any): this;
lt(value: any): this;
lte(value: any): this;
in(value: any[]): this;
nin(value: any[]): this;
// Query options
select(fields: string | object): this;
sort(fields: string | object): this;
limit(val: number): this;
skip(val: number): this;
// Population
populate(path: string | PopulateOptions): this;
// Execution
exec(): Promise<ResultType>;
then(resolve?: Function, reject?: Function): Promise<ResultType>;
}MongoDB aggregation pipeline builder with stage methods, type safety, and execution options for complex data processing.
interface Aggregate<T> {
// Pipeline stages
match(conditions: FilterQuery<T>): this;
group(arg: any): this;
project(arg: any): this;
sort(arg: any): this;
limit(num: number): this;
skip(num: number): this;
lookup(options: any): this;
unwind(field: string | object): this;
// Execution
exec(): Promise<T[]>;
cursor(): AggregateCursor<T>;
}Comprehensive error system with specific error types for different failure scenarios, validation errors, and MongoDB operation errors.
// Base error classes
class MongooseError extends Error {}
class CastError extends MongooseError {
path: string;
value: any;
kind: string;
}
class ValidationError extends MongooseError {
errors: { [path: string]: ValidatorError };
}
class ValidatorError extends MongooseError {
path: string;
value: any;
kind: string;
}
// Specialized errors
class DocumentNotFoundError extends MongooseError {}
class VersionError extends MongooseError {}
class OverwriteModelError extends MongooseError {}Global configuration, helper functions, type utilities, and debugging tools for Mongoose applications.
// Global configuration
mongoose.set(option: string, value: any): typeof mongoose;
mongoose.get(option: string): any;
// Utilities
mongoose.isValidObjectId(value: any): boolean;
mongoose.sanitizeFilter(filter: any): any;
mongoose.pluralize(fn?: Function): Function;
mongoose.plugin(fn: Function, opts?: any): typeof mongoose;
// Types and constants
mongoose.Types.ObjectId, mongoose.Types.Decimal128;
mongoose.STATES: { disconnected: 0, connected: 1, connecting: 2, disconnecting: 3 };// Core interfaces
interface ConnectOptions {
bufferCommands?: boolean;
maxPoolSize?: number;
serverSelectionTimeoutMS?: number;
socketTimeoutMS?: number;
family?: number;
// ... additional MongoDB connection options
}
interface SchemaOptions {
autoIndex?: boolean;
autoCreate?: boolean;
bufferCommands?: boolean;
capped?: boolean | number | { size?: number; max?: number; };
collection?: string;
discriminatorKey?: string;
id?: boolean;
_id?: boolean;
minimize?: boolean;
read?: string;
writeConcern?: any;
shardKey?: any;
strict?: boolean;
strictQuery?: boolean;
toJSON?: any;
toObject?: any;
typeKey?: string;
validateBeforeSave?: boolean;
versionKey?: string | boolean;
timestamps?: boolean | SchemaTimestampsConfig;
}
interface SchemaTimestampsConfig {
createdAt?: boolean | string;
updatedAt?: boolean | string;
currentTime?: () => Date;
}
// MongoDB operation result types
interface UpdateResult {
acknowledged: boolean;
modifiedCount: number;
upsertedId?: ObjectId;
upsertedCount: number;
matchedCount: number;
}
interface DeleteResult {
acknowledged: boolean;
deletedCount: number;
}