or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aggregation.mdconnection.mddocument.mderrors.mdindex.mdmodel.mdquery.mdschema.mdutilities.md

utilities.mddocs/

0

# Utilities and Configuration

1

2

Global configuration, helper functions, type utilities, and debugging tools for Mongoose applications with comprehensive customization options.

3

4

## Capabilities

5

6

### Global Configuration

7

8

Configure Mongoose behavior globally with various options for connections, schemas, and operations.

9

10

```javascript { .api }

11

/**

12

* Set global Mongoose option

13

* @param option - Option name

14

* @param value - Option value

15

* @returns Mongoose instance

16

*/

17

mongoose.set(option: string, value: any): typeof mongoose;

18

19

/**

20

* Get global Mongoose option value

21

* @param option - Option name

22

* @returns Current option value

23

*/

24

mongoose.get(option: string): any;

25

26

// Available global options

27

type MongooseOptions = {

28

/** Auto-create indexes from schema */

29

autoIndex: boolean;

30

31

/** Auto-create collections */

32

autoCreate: boolean;

33

34

/** Auto-create search indexes */

35

autoSearchIndex: boolean;

36

37

/** Buffer commands when disconnected */

38

bufferCommands: boolean;

39

40

/** Max number of buffered commands */

41

bufferMaxEntries: number;

42

43

/** Use createIndex instead of deprecated ensureIndex */

44

useCreateIndex: boolean;

45

46

/** Use findOneAndUpdate instead of deprecated findAndModify */

47

useFindAndModify: boolean;

48

49

/** Use new URL parser */

50

useNewUrlParser: boolean;

51

52

/** Use unified topology */

53

useUnifiedTopology: boolean;

54

55

/** Default strict mode for schemas */

56

strict: boolean | 'throw';

57

58

/** Strict mode for queries */

59

strictQuery: boolean | 'throw';

60

61

/** Strict mode for populate */

62

strictPopulate: boolean;

63

64

/** Run validators on update operations */

65

runValidators: boolean;

66

67

/** Return original document in findAndModify operations */

68

returnOriginal: boolean;

69

70

/** Minimize empty objects in documents */

71

minimize: boolean;

72

73

/** Automatically translate field aliases */

74

translateAliases: boolean;

75

76

/** Automatically sanitize query filters */

77

sanitizeFilter: boolean;

78

79

/** Transform POJOs to Mixed type */

80

typePojoToMixed: boolean;

81

82

/** Auto-select populated paths */

83

selectPopulatedPaths: boolean;

84

85

/** Maximum time for operations */

86

maxTimeMS: number;

87

88

/** Default transform function */

89

transform: Function;

90

91

/** JSON transform function */

92

toJSON: Function;

93

94

/** Object transform function */

95

toObject: Function;

96

};

97

```

98

99

**Usage Examples:**

100

101

```javascript

102

// Common global configurations

103

mongoose.set('strictQuery', false); // Allow flexible queries

104

mongoose.set('autoIndex', false); // Disable auto-indexing in production

105

mongoose.set('bufferCommands', false); // Fail fast when disconnected

106

mongoose.set('sanitizeFilter', true); // Auto-sanitize query filters

107

mongoose.set('returnOriginal', false); // Return updated documents

108

109

// Development vs Production settings

110

if (process.env.NODE_ENV === 'development') {

111

mongoose.set('debug', true); // Enable query logging

112

mongoose.set('autoIndex', true); // Auto-create indexes

113

} else {

114

mongoose.set('autoIndex', false); // Manual index management

115

mongoose.set('bufferMaxEntries', 0); // Fail immediately if disconnected

116

}

117

118

// Validation settings

119

mongoose.set('runValidators', true); // Validate on updates

120

mongoose.set('strictQuery', 'throw'); // Throw on invalid query fields

121

122

// Get current settings

123

console.log('Auto-indexing:', mongoose.get('autoIndex'));

124

console.log('Strict mode:', mongoose.get('strict'));

125

```

126

127

### Plugin System

128

129

Register global and schema-specific plugins for extending Mongoose functionality.

130

131

```javascript { .api }

132

/**

133

* Register global plugin

134

* @param fn - Plugin function

135

* @param opts - Plugin options

136

* @returns Mongoose instance

137

*/

138

mongoose.plugin(fn: Function, opts?: any): typeof mongoose;

139

140

/**

141

* Plugin function signature

142

* @param schema - Schema to apply plugin to

143

* @param options - Plugin options

144

*/

145

type PluginFunction = (schema: Schema, options?: any) => void;

146

```

147

148

**Usage Examples:**

149

150

```javascript

151

// Built-in plugins

152

const mongooseLeanDefaults = require('mongoose-lean-defaults');

153

const mongooseSlugPlugin = require('mongoose-slug-plugin');

154

155

// Register global plugins

156

mongoose.plugin(mongooseLeanDefaults);

157

mongoose.plugin(mongooseSlugPlugin, { field: 'title' });

158

159

// Custom timestamp plugin

160

function timestampPlugin(schema, options) {

161

const { createdPath = 'createdAt', updatedPath = 'updatedAt' } = options || {};

162

163

schema.add({

164

[createdPath]: { type: Date, default: Date.now },

165

[updatedPath]: { type: Date, default: Date.now }

166

});

167

168

schema.pre('save', function() {

169

if (this.isModified() && !this.isNew) {

170

this[updatedPath] = new Date();

171

}

172

});

173

174

schema.pre(['updateOne', 'updateMany', 'findOneAndUpdate'], function() {

175

this.set({ [updatedPath]: new Date() });

176

});

177

}

178

179

// Apply to all schemas

180

mongoose.plugin(timestampPlugin);

181

182

// Apply to specific schema with options

183

userSchema.plugin(timestampPlugin, {

184

createdPath: 'created',

185

updatedPath: 'modified'

186

});

187

188

// Validation plugin

189

function validationPlugin(schema) {

190

schema.post('save', function(error, doc, next) {

191

if (error.name === 'MongoError' && error.code === 11000) {

192

next(new Error('Duplicate key error'));

193

} else {

194

next(error);

195

}

196

});

197

}

198

199

mongoose.plugin(validationPlugin);

200

```

201

202

### Type Utilities

203

204

Utility functions for working with MongoDB types and ObjectIds.

205

206

```javascript { .api }

207

/**

208

* Check if value is a valid ObjectId

209

* @param value - Value to check

210

* @returns true if valid ObjectId

211

*/

212

mongoose.isValidObjectId(value: any): boolean;

213

214

/**

215

* Check if value is ObjectId or 24-character hex string

216

* @param value - Value to check

217

* @returns true if ObjectId or hex string

218

*/

219

mongoose.isObjectIdOrHexString(value: any): boolean;

220

221

/**

222

* Cast value to ObjectId

223

* @param value - Value to cast

224

* @returns ObjectId instance

225

*/

226

mongoose.Types.ObjectId(value?: string | number | ObjectId): ObjectId;

227

228

/**

229

* Sanitize query filters against injection attacks

230

* @param filter - Query filter object

231

* @returns Sanitized filter object

232

*/

233

mongoose.sanitizeFilter<T>(filter: FilterQuery<T>): FilterQuery<T>;

234

235

/**

236

* Mark object as trusted (skip query sanitization)

237

* @param obj - Object to mark as trusted

238

* @returns Trusted object

239

*/

240

mongoose.trusted(obj: any): any;

241

242

/**

243

* Cast value to specified type

244

* @param type - Schema type to cast to

245

* @param value - Value to cast

246

* @param path - Path name for error reporting

247

* @param doc - Document context

248

* @returns Cast value

249

*/

250

mongoose.cast(type: any, value: any, path?: string, doc?: Document): any;

251

252

/**

253

* Get current timestamp function

254

* @returns Function that returns current Date

255

*/

256

mongoose.now(): () => Date;

257

258

/**

259

* Skip middleware execution for a result

260

* @param result - Result to skip middleware for

261

* @returns Modified result

262

*/

263

mongoose.skipMiddlewareFunction(result: any): any;

264

265

/**

266

* Overwrite middleware result

267

* @param result - Result to overwrite

268

* @returns Modified result

269

*/

270

mongoose.overwriteMiddlewareResult(result: any): any;

271

272

/**

273

* Set custom MongoDB driver

274

* @param driver - MongoDB driver object

275

* @returns Mongoose instance

276

*/

277

mongoose.setDriver(driver: any): typeof mongoose;

278

279

/**

280

* Remove undefined properties from object

281

* @param val - Object to clean

282

* @returns Object without undefined properties

283

*/

284

mongoose.omitUndefined<T>(val: T): T;

285

286

/**

287

* Generate new ObjectId

288

* @returns New ObjectId

289

*/

290

mongoose.Types.ObjectId(): ObjectId;

291

292

/**

293

* Get ObjectId from timestamp

294

* @param timestamp - Unix timestamp

295

* @returns ObjectId representing the timestamp

296

*/

297

mongoose.Types.ObjectId.createFromTime(timestamp: number): ObjectId;

298

299

/**

300

* Check if two ObjectIds are equal

301

* @param a - First ObjectId

302

* @param b - Second ObjectId

303

* @returns true if equal

304

*/

305

ObjectId.prototype.equals(b: ObjectId): boolean;

306

307

/**

308

* Get timestamp from ObjectId

309

* @returns Date object from ObjectId timestamp

310

*/

311

ObjectId.prototype.getTimestamp(): Date;

312

```

313

314

**Usage Examples:**

315

316

```javascript

317

// Validate ObjectIds

318

const userId = req.params.id;

319

if (!mongoose.isValidObjectId(userId)) {

320

return res.status(400).json({ error: 'Invalid user ID' });

321

}

322

323

// Check if string can be ObjectId

324

const possibleId = 'somestring';

325

if (mongoose.isObjectIdOrHexString(possibleId)) {

326

const user = await User.findById(possibleId);

327

}

328

329

// Generate ObjectIds

330

const newId = new mongoose.Types.ObjectId();

331

console.log('New ID:', newId.toString());

332

333

// ObjectId from string

334

const id = new mongoose.Types.ObjectId('507f1f77bcf86cd799439011');

335

336

// ObjectId from timestamp

337

const timestampId = mongoose.Types.ObjectId.createFromTime(Math.floor(Date.now() / 1000));

338

console.log('ID from timestamp:', timestampId);

339

340

// Extract timestamp from ObjectId

341

const createdAt = userId.getTimestamp();

342

console.log('Document created at:', createdAt);

343

344

// Compare ObjectIds

345

if (user1._id.equals(user2._id)) {

346

console.log('Same user');

347

}

348

349

// ObjectId utilities in queries

350

const recentIds = await User.find({

351

_id: {

352

$gte: mongoose.Types.ObjectId.createFromTime(Date.now() / 1000 - 3600) // Last hour

353

}

354

}).select('_id name');

355

```

356

357

### Collection Name Management

358

359

Configure how Mongoose generates collection names from model names.

360

361

```javascript { .api }

362

/**

363

* Get or set pluralization function

364

* @param fn - Pluralization function (optional)

365

* @returns Current pluralization function

366

*/

367

mongoose.pluralize(fn?: Function): Function;

368

369

// Default pluralization function signature

370

type PluralizationFunction = (name: string) => string;

371

```

372

373

**Usage Examples:**

374

375

```javascript

376

// Default pluralization

377

console.log(mongoose.pluralize()('User')); // 'users'

378

console.log(mongoose.pluralize()('Person')); // 'people'

379

console.log(mongoose.pluralize()('Child')); // 'children'

380

381

// Custom pluralization

382

mongoose.pluralize((name) => {

383

// Simple pluralization - just add 's'

384

return name.toLowerCase() + 's';

385

});

386

387

// Disable pluralization

388

mongoose.pluralize(null);

389

390

// Complex custom pluralization

391

const inflection = require('inflection');

392

mongoose.pluralize((name) => {

393

return inflection.pluralize(name).toLowerCase();

394

});

395

396

// Per-model collection names (overrides pluralization)

397

const User = mongoose.model('User', userSchema, 'custom_users');

398

```

399

400

### Query Filter Sanitization

401

402

Protect against NoSQL injection attacks by sanitizing query filters.

403

404

```javascript { .api }

405

/**

406

* Sanitize query filter against injection attacks

407

* @param filter - Query filter object

408

* @returns Sanitized filter

409

*/

410

mongoose.sanitizeFilter<T>(filter: FilterQuery<T>): FilterQuery<T>;

411

412

/**

413

* Mark object as trusted (bypass sanitization)

414

* @param obj - Object to mark as trusted

415

* @returns Trusted object

416

*/

417

mongoose.trusted(obj: any): any;

418

```

419

420

**Usage Examples:**

421

422

```javascript

423

// Enable automatic sanitization

424

mongoose.set('sanitizeFilter', true);

425

426

// Manual sanitization

427

const userInput = req.body.filter; // Could contain { $where: 'malicious code' }

428

const safeFilter = mongoose.sanitizeFilter(userInput);

429

const users = await User.find(safeFilter);

430

431

// Trusted objects bypass sanitization

432

const adminQuery = mongoose.trusted({

433

$where: 'this.role === "admin"' // Intentional $where usage

434

});

435

const admins = await User.find(adminQuery);

436

437

// Sanitization in practice

438

app.post('/users/search', async (req, res) => {

439

try {

440

// req.body might contain: { name: { $ne: null }, $where: "..." }

441

const filter = mongoose.sanitizeFilter(req.body);

442

// Sanitized to: { name: { $eq: { $ne: null } }, "$where": { $eq: "..." } }

443

444

const users = await User.find(filter);

445

res.json(users);

446

} catch (error) {

447

res.status(500).json({ error: error.message });

448

}

449

});

450

451

// Custom sanitization

452

function customSanitize(obj) {

453

const sanitized = mongoose.sanitizeFilter(obj);

454

455

// Additional custom logic

456

if (sanitized.$text && !user.hasTextSearchPermission) {

457

delete sanitized.$text;

458

}

459

460

return sanitized;

461

}

462

```

463

464

### Connection State Management

465

466

Monitor and manage connection states with constants and utilities.

467

468

```javascript { .api }

469

/**

470

* Connection state constants

471

*/

472

mongoose.STATES: {

473

disconnected: 0;

474

connected: 1;

475

connecting: 2;

476

disconnecting: 3;

477

uninitialized: 99;

478

};

479

480

/**

481

* Check connection readiness

482

* @returns true if connected

483

*/

484

mongoose.connection.readyState === mongoose.STATES.connected;

485

```

486

487

**Usage Examples:**

488

489

```javascript

490

// Check connection state

491

function isConnected() {

492

return mongoose.connection.readyState === mongoose.STATES.connected;

493

}

494

495

function getConnectionState() {

496

const state = mongoose.connection.readyState;

497

const states = {

498

[mongoose.STATES.disconnected]: 'disconnected',

499

[mongoose.STATES.connected]: 'connected',

500

[mongoose.STATES.connecting]: 'connecting',

501

[mongoose.STATES.disconnecting]: 'disconnecting',

502

[mongoose.STATES.uninitialized]: 'uninitialized'

503

};

504

return states[state] || 'unknown';

505

}

506

507

// Wait for connection

508

async function waitForConnection(timeout = 10000) {

509

return new Promise((resolve, reject) => {

510

if (mongoose.connection.readyState === mongoose.STATES.connected) {

511

return resolve(true);

512

}

513

514

const timer = setTimeout(() => {

515

reject(new Error('Connection timeout'));

516

}, timeout);

517

518

mongoose.connection.once('connected', () => {

519

clearTimeout(timer);

520

resolve(true);

521

});

522

523

mongoose.connection.once('error', (error) => {

524

clearTimeout(timer);

525

reject(error);

526

});

527

});

528

}

529

530

// Health check endpoint

531

app.get('/health', (req, res) => {

532

const dbState = getConnectionState();

533

res.json({

534

status: dbState === 'connected' ? 'healthy' : 'unhealthy',

535

database: dbState,

536

timestamp: new Date().toISOString()

537

});

538

});

539

```

540

541

### Index Management

542

543

Utilities for managing database indexes across all models.

544

545

```javascript { .api }

546

/**

547

* Synchronize indexes for all models

548

* @param options - Sync options

549

* @returns Promise resolving to sync results

550

*/

551

mongoose.syncIndexes(options?: SyncIndexesOptions): Promise<{ [modelName: string]: string[] }>;

552

553

interface SyncIndexesOptions {

554

/** Continue on error */

555

continueOnError?: boolean;

556

557

/** Skip specific models */

558

skip?: string[];

559

560

/** Only sync specific models */

561

only?: string[];

562

}

563

```

564

565

**Usage Examples:**

566

567

```javascript

568

// Sync all indexes

569

const results = await mongoose.syncIndexes();

570

console.log('Index sync results:', results);

571

572

// Sync with options

573

const results = await mongoose.syncIndexes({

574

continueOnError: true,

575

skip: ['TempModel'] // Skip temporary models

576

});

577

578

// Production deployment script

579

async function deployIndexes() {

580

try {

581

console.log('Syncing database indexes...');

582

const results = await mongoose.syncIndexes();

583

584

Object.keys(results).forEach(modelName => {

585

const operations = results[modelName];

586

if (operations.length > 0) {

587

console.log(`${modelName}: ${operations.join(', ')}`);

588

}

589

});

590

591

console.log('Index synchronization completed');

592

} catch (error) {

593

console.error('Index sync failed:', error);

594

throw error;

595

}

596

}

597

598

// Manual index management

599

async function manageIndexes() {

600

// Create indexes for specific model

601

await User.createIndexes();

602

603

// List existing indexes

604

const indexes = await User.listIndexes();

605

console.log('User indexes:', indexes);

606

607

// Sync indexes for specific model

608

const userSync = await User.syncIndexes();

609

console.log('User index operations:', userSync);

610

}

611

```

612

613

### Additional Utilities

614

615

Additional helper functions and middleware utilities for advanced Mongoose usage.

616

617

```javascript { .api }

618

/**

619

* Get current timestamp (Date.now)

620

* @returns Current timestamp function

621

*/

622

mongoose.now(): () => Date;

623

624

/**

625

* Cast value to schema type

626

* @param type - Schema type or type name

627

* @param value - Value to cast

628

* @param path - Field path (optional)

629

* @param doc - Document context (optional)

630

* @returns Casted value

631

*/

632

mongoose.cast(type: any, value: any, path?: string, doc?: Document): any;

633

634

/**

635

* Set MongoDB driver instance

636

* @param driver - MongoDB driver to use

637

* @returns Mongoose instance

638

*/

639

mongoose.setDriver(driver: any): typeof mongoose;

640

641

/**

642

* Skip middleware execution and return result

643

* @param result - Result to return, skipping middleware

644

* @returns Special result object that skips middleware

645

*/

646

mongoose.skipMiddlewareFunction(result: any): any;

647

648

/**

649

* Overwrite middleware result

650

* @param result - New result to use instead of middleware result

651

* @returns Special result object that overwrites middleware result

652

*/

653

mongoose.overwriteMiddlewareResult(result: any): any;

654

```

655

656

**Usage Examples:**

657

658

```javascript

659

// Get current timestamp function

660

const timestampFn = mongoose.now();

661

console.log('Current time:', timestampFn()); // Current Date

662

663

// Cast values using schema types

664

const schema = new mongoose.Schema({ age: Number });

665

const castedAge = mongoose.cast(Number, '25'); // 25 (number)

666

const castedId = mongoose.cast(mongoose.Schema.Types.ObjectId, '507f1f77bcf86cd799439011');

667

668

// Set custom driver (advanced usage)

669

const customDriver = require('./custom-mongodb-driver');

670

mongoose.setDriver(customDriver);

671

672

// Middleware control (advanced)

673

userSchema.pre('save', function() {

674

if (this.skipValidation) {

675

return mongoose.skipMiddlewareFunction(this);

676

}

677

678

// Normal middleware logic

679

this.updatedAt = new Date();

680

});

681

682

userSchema.post('save', function(result) {

683

if (this.customResult) {

684

return mongoose.overwriteMiddlewareResult(this.customResult);

685

}

686

return result;

687

});

688

```

689

690

### Native Driver Access

691

692

Access underlying MongoDB driver and query builder for advanced operations.

693

694

```javascript { .api }

695

/**

696

* Native MongoDB driver reference

697

*/

698

mongoose.mongo: typeof mongodb;

699

700

/**

701

* MQuery query builder reference

702

*/

703

mongoose.mquery: typeof mquery;

704

```

705

706

**Usage Examples:**

707

708

```javascript

709

// Access native MongoDB driver

710

const { MongoClient, ObjectId } = mongoose.mongo;

711

712

// Use native operations

713

const db = mongoose.connection.db;

714

const result = await db.collection('users').aggregate([

715

{ $match: { status: 'active' } },

716

{ $group: { _id: '$department', count: { $sum: 1 } } }

717

]).toArray();

718

719

// Create native ObjectId

720

const nativeId = new mongoose.mongo.ObjectId();

721

722

// Access mquery for query building

723

const mquery = mongoose.mquery;

724

const query = mquery().find({ status: 'active' }).limit(10);

725

726

// Check driver versions

727

console.log('MongoDB driver version:', mongoose.mongo.version);

728

console.log('MQuery version:', mongoose.mquery.version);

729

```

730

731

### Debugging and Development

732

733

Development tools for debugging queries, performance monitoring, and troubleshooting.

734

735

```javascript { .api }

736

/**

737

* Enable query debugging

738

* @param enabled - Enable debug mode

739

* @param options - Debug options

740

* @returns Mongoose instance

741

*/

742

mongoose.set('debug', enabled: boolean | Function | DebugOptions): typeof mongoose;

743

744

interface DebugOptions {

745

/** Include shell commands */

746

shell?: boolean;

747

748

/** Custom debug function */

749

fn?: (collectionName: string, method: string, query: any, doc?: any) => void;

750

}

751

752

/**

753

* Get Mongoose version

754

*/

755

mongoose.version: string;

756

757

/**

758

* Access native MongoDB driver

759

*/

760

mongoose.mongo: typeof mongodb;

761

762

/**

763

* Access mquery (query builder)

764

*/

765

mongoose.mquery: typeof mquery;

766

```

767

768

**Usage Examples:**

769

770

```javascript

771

// Enable query debugging

772

mongoose.set('debug', true);

773

774

// Custom debug function

775

mongoose.set('debug', (collectionName, method, query, doc) => {

776

console.log(`[${new Date().toISOString()}] ${collectionName}.${method}`,

777

JSON.stringify(query, null, 2));

778

});

779

780

// Conditional debugging

781

if (process.env.NODE_ENV === 'development') {

782

mongoose.set('debug', true);

783

}

784

785

// Debug with shell commands

786

mongoose.set('debug', { shell: true });

787

788

// Performance monitoring

789

const originalExec = mongoose.Query.prototype.exec;

790

mongoose.Query.prototype.exec = function() {

791

const startTime = Date.now();

792

const result = originalExec.call(this);

793

794

if (result && typeof result.then === 'function') {

795

return result.then(res => {

796

const duration = Date.now() - startTime;

797

if (duration > 100) { // Log slow queries

798

console.warn(`Slow query (${duration}ms):`, this.getQuery());

799

}

800

return res;

801

});

802

}

803

804

return result;

805

};

806

807

// Version information

808

console.log('Mongoose version:', mongoose.version);

809

console.log('MongoDB driver version:', mongoose.mongo.version);

810

811

// Native driver access

812

const db = mongoose.connection.db;

813

const nativeCollection = db.collection('users');

814

const count = await nativeCollection.countDocuments({});

815

```

816

817

## Types

818

819

```javascript { .api }

820

interface MongooseGlobals {

821

/** Mongoose version string */

822

version: string;

823

824

/** Connection state constants */

825

STATES: {

826

disconnected: 0;

827

connected: 1;

828

connecting: 2;

829

disconnecting: 3;

830

uninitialized: 99;

831

};

832

833

/** Type constructors */

834

Types: {

835

ObjectId: typeof ObjectId;

836

Decimal128: typeof Decimal128;

837

Array: typeof MongooseArray;

838

DocumentArray: typeof MongooseDocumentArray;

839

Buffer: typeof MongooseBuffer;

840

Map: typeof MongooseMap;

841

UUID: typeof UUID;

842

};

843

844

/** Schema type constructors */

845

SchemaTypes: {

846

String: typeof String;

847

Number: typeof Number;

848

Date: typeof Date;

849

Boolean: typeof Boolean;

850

ObjectId: typeof ObjectId;

851

Buffer: typeof Buffer;

852

Mixed: typeof Mixed;

853

Array: typeof Array;

854

Decimal128: typeof Decimal128;

855

Map: typeof Map;

856

UUID: typeof UUID;

857

BigInt: typeof BigInt;

858

};

859

860

/** Error classes */

861

Error: {

862

MongooseError: typeof MongooseError;

863

ValidationError: typeof ValidationError;

864

ValidatorError: typeof ValidatorError;

865

CastError: typeof CastError;

866

DocumentNotFoundError: typeof DocumentNotFoundError;

867

VersionError: typeof VersionError;

868

ParallelSaveError: typeof ParallelSaveError;

869

MissingSchemaError: typeof MissingSchemaError;

870

OverwriteModelError: typeof OverwriteModelError;

871

};

872

873

/** Native MongoDB driver reference */

874

mongo: typeof mongodb;

875

876

/** Query builder reference */

877

mquery: typeof mquery;

878

}

879

880

// Utility type helpers

881

type ObjectIdLike = string | ObjectId;

882

type FilterQuery<T> = { [P in keyof T]?: T[P] | QuerySelector<T[P]> } & QuerySelector<T>;

883

type UpdateQuery<T> = Partial<T> & MongoUpdateOperators;

884

type ProjectionType<T> = string | { [K in keyof T]?: 1 | 0 | boolean };

885

```