0
# Mongoose
1
2
Mongoose 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.
3
4
## Package Information
5
6
- **Package Name**: mongoose
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript definitions)
9
- **Installation**: `npm install mongoose`
10
11
## Core Imports
12
13
```javascript
14
const mongoose = require('mongoose');
15
```
16
17
ES6/TypeScript:
18
19
```typescript
20
import mongoose from 'mongoose';
21
// Or with named imports
22
import { Schema, model, connect } from 'mongoose';
23
```
24
25
## Basic Usage
26
27
```javascript
28
const mongoose = require('mongoose');
29
30
// Connect to MongoDB
31
await mongoose.connect('mongodb://localhost:27017/myapp');
32
33
// Define a schema
34
const userSchema = new mongoose.Schema({
35
name: { type: String, required: true },
36
email: { type: String, required: true, unique: true },
37
age: { type: Number, min: 0 },
38
createdAt: { type: Date, default: Date.now }
39
});
40
41
// Create a model
42
const User = mongoose.model('User', userSchema);
43
44
// Create and save a document
45
const user = new User({
46
name: 'John Doe',
47
email: 'john@example.com',
48
age: 30
49
});
50
await user.save();
51
52
// Query documents
53
const users = await User.find({ age: { $gte: 18 } });
54
```
55
56
## Architecture
57
58
Mongoose is built around several key components:
59
60
- **Connection Management**: Database connection handling with automatic reconnection and connection pooling
61
- **Schema Definition**: Structured data modeling with type definitions, validation rules, and business logic
62
- **Document System**: Active Record pattern with instance methods, validation, and change tracking
63
- **Query System**: Fluent query builder with method chaining, population, and lean queries
64
- **Middleware System**: Pre/post hooks for document and query operations
65
- **Type System**: Complete TypeScript integration with schema type inference
66
67
## Capabilities
68
69
### Connection Management
70
71
Database connection establishment, management, and configuration with support for multiple connections and automatic reconnection.
72
73
```javascript { .api }
74
// Static methods
75
mongoose.connect(uri: string, options?: ConnectOptions): Promise<typeof mongoose>;
76
mongoose.createConnection(uri: string, options?: ConnectOptions): Connection;
77
mongoose.disconnect(): Promise<void>;
78
79
// Connection events and properties
80
interface Connection {
81
readyState: number;
82
db: mongodb.Db;
83
models: { [key: string]: Model<any> };
84
}
85
```
86
87
[Connection Management](./connection.md)
88
89
### Schema Definition
90
91
Define document structure, validation rules, indexes, virtual properties, and middleware with a rich schema type system.
92
93
```javascript { .api }
94
class Schema<T = any> {
95
constructor(definition?: SchemaDefinition<T>, options?: SchemaOptions);
96
97
add(obj: SchemaDefinition<T>, prefix?: string): this;
98
path(path: string): SchemaType | undefined;
99
virtual(name: string): VirtualType;
100
index(fields: any, options?: any): this;
101
pre(method: string, fn: Function): this;
102
post(method: string, fn: Function): this;
103
method(name: string, fn: Function): this;
104
static(name: string, fn: Function): this;
105
}
106
107
// Built-in schema types
108
Schema.Types.String, Schema.Types.Number, Schema.Types.Date,
109
Schema.Types.Boolean, Schema.Types.ObjectId, Schema.Types.Array,
110
Schema.Types.Mixed, Schema.Types.Decimal128, Schema.Types.Map,
111
Schema.Types.UUID, Schema.Types.BigInt
112
```
113
114
[Schema Definition](./schema.md)
115
116
### Model Operations
117
118
Model class providing static methods for CRUD operations, queries, aggregation, and document management with full MongoDB feature support.
119
120
```javascript { .api }
121
interface Model<T> {
122
// Document creation
123
static create<T>(doc: T): Promise<T>;
124
static insertMany<T>(docs: T[]): Promise<T[]>;
125
126
// Queries
127
static find<T>(filter: FilterQuery<T>): Query<T[], T>;
128
static findOne<T>(filter: FilterQuery<T>): Query<T | null, T>;
129
static findById<T>(id: any): Query<T | null, T>;
130
131
// Updates
132
static updateOne<T>(filter: FilterQuery<T>, update: UpdateQuery<T>): Query<UpdateResult, T>;
133
static findOneAndUpdate<T>(filter: FilterQuery<T>, update: UpdateQuery<T>): Query<T | null, T>;
134
135
// Deletions
136
static deleteOne<T>(filter: FilterQuery<T>): Query<DeleteResult, T>;
137
static findOneAndDelete<T>(filter: FilterQuery<T>): Query<T | null, T>;
138
}
139
```
140
141
[Model Operations](./model.md)
142
143
### Document Manipulation
144
145
Document instance methods for saving, validation, field access, and lifecycle management with change tracking and middleware.
146
147
```javascript { .api }
148
interface Document {
149
save(): Promise<this>;
150
validate(): Promise<void>;
151
152
set(path: string, val: any): this;
153
get(path: string): any;
154
markModified(path: string): void;
155
156
toObject(options?: ToObjectOptions): any;
157
toJSON(options?: ToObjectOptions): any;
158
159
isModified(path?: string): boolean;
160
isNew: boolean;
161
id: string;
162
_id: ObjectId;
163
}
164
```
165
166
[Document Manipulation](./document.md)
167
168
### Query Building
169
170
Fluent query builder with method chaining, population, lean queries, and advanced MongoDB query operations.
171
172
```javascript { .api }
173
interface Query<ResultType, DocType> {
174
// Query conditions
175
where(path: string, val?: any): this;
176
equals(value: any): this;
177
gt(value: any): this;
178
gte(value: any): this;
179
lt(value: any): this;
180
lte(value: any): this;
181
in(value: any[]): this;
182
nin(value: any[]): this;
183
184
// Query options
185
select(fields: string | object): this;
186
sort(fields: string | object): this;
187
limit(val: number): this;
188
skip(val: number): this;
189
190
// Population
191
populate(path: string | PopulateOptions): this;
192
193
// Execution
194
exec(): Promise<ResultType>;
195
then(resolve?: Function, reject?: Function): Promise<ResultType>;
196
}
197
```
198
199
[Query Building](./query.md)
200
201
### Aggregation Pipeline
202
203
MongoDB aggregation pipeline builder with stage methods, type safety, and execution options for complex data processing.
204
205
```javascript { .api }
206
interface Aggregate<T> {
207
// Pipeline stages
208
match(conditions: FilterQuery<T>): this;
209
group(arg: any): this;
210
project(arg: any): this;
211
sort(arg: any): this;
212
limit(num: number): this;
213
skip(num: number): this;
214
lookup(options: any): this;
215
unwind(field: string | object): this;
216
217
// Execution
218
exec(): Promise<T[]>;
219
cursor(): AggregateCursor<T>;
220
}
221
```
222
223
[Aggregation Pipeline](./aggregation.md)
224
225
### Error Handling
226
227
Comprehensive error system with specific error types for different failure scenarios, validation errors, and MongoDB operation errors.
228
229
```javascript { .api }
230
// Base error classes
231
class MongooseError extends Error {}
232
class CastError extends MongooseError {
233
path: string;
234
value: any;
235
kind: string;
236
}
237
class ValidationError extends MongooseError {
238
errors: { [path: string]: ValidatorError };
239
}
240
class ValidatorError extends MongooseError {
241
path: string;
242
value: any;
243
kind: string;
244
}
245
246
// Specialized errors
247
class DocumentNotFoundError extends MongooseError {}
248
class VersionError extends MongooseError {}
249
class OverwriteModelError extends MongooseError {}
250
```
251
252
[Error Handling](./errors.md)
253
254
### Utilities and Configuration
255
256
Global configuration, helper functions, type utilities, and debugging tools for Mongoose applications.
257
258
```javascript { .api }
259
// Global configuration
260
mongoose.set(option: string, value: any): typeof mongoose;
261
mongoose.get(option: string): any;
262
263
// Utilities
264
mongoose.isValidObjectId(value: any): boolean;
265
mongoose.sanitizeFilter(filter: any): any;
266
mongoose.pluralize(fn?: Function): Function;
267
mongoose.plugin(fn: Function, opts?: any): typeof mongoose;
268
269
// Types and constants
270
mongoose.Types.ObjectId, mongoose.Types.Decimal128;
271
mongoose.STATES: { disconnected: 0, connected: 1, connecting: 2, disconnecting: 3 };
272
```
273
274
[Utilities and Configuration](./utilities.md)
275
276
## Types
277
278
```javascript { .api }
279
// Core interfaces
280
interface ConnectOptions {
281
bufferCommands?: boolean;
282
maxPoolSize?: number;
283
serverSelectionTimeoutMS?: number;
284
socketTimeoutMS?: number;
285
family?: number;
286
// ... additional MongoDB connection options
287
}
288
289
interface SchemaOptions {
290
autoIndex?: boolean;
291
autoCreate?: boolean;
292
bufferCommands?: boolean;
293
capped?: boolean | number | { size?: number; max?: number; };
294
collection?: string;
295
discriminatorKey?: string;
296
id?: boolean;
297
_id?: boolean;
298
minimize?: boolean;
299
read?: string;
300
writeConcern?: any;
301
shardKey?: any;
302
strict?: boolean;
303
strictQuery?: boolean;
304
toJSON?: any;
305
toObject?: any;
306
typeKey?: string;
307
validateBeforeSave?: boolean;
308
versionKey?: string | boolean;
309
timestamps?: boolean | SchemaTimestampsConfig;
310
}
311
312
interface SchemaTimestampsConfig {
313
createdAt?: boolean | string;
314
updatedAt?: boolean | string;
315
currentTime?: () => Date;
316
}
317
318
// MongoDB operation result types
319
interface UpdateResult {
320
acknowledged: boolean;
321
modifiedCount: number;
322
upsertedId?: ObjectId;
323
upsertedCount: number;
324
matchedCount: number;
325
}
326
327
interface DeleteResult {
328
acknowledged: boolean;
329
deletedCount: number;
330
}
331
```