mongoose
Mongoose ODM for MongoDB and Node.js. Use for schemas, models, queries, validation, middleware, population, aggregation, and MongoDB database operations in JavaScript/TypeScript applications.
When & Why to Use This Skill
This Mongoose skill serves as a comprehensive developer companion for MongoDB and Node.js integration. It provides expert guidance on Object Data Modeling (ODM), enabling developers to efficiently manage schemas, models, and complex queries while ensuring data integrity through validation and middleware. It is an essential tool for building scalable JavaScript and TypeScript backend applications with robust database layers.
Use Cases
- Architecting and implementing structured MongoDB schemas with built-in validation and type safety for Node.js backends.
- Debugging complex database operations, including multi-level population, aggregation pipelines, and custom middleware logic.
- Generating optimized Mongoose queries and boilerplate code for models to accelerate the development of RESTful or GraphQL APIs.
- Learning and applying best practices for MongoDB connection management, indexing, and performance optimization within a TypeScript environment.
| name | mongoose |
|---|---|
| description | Mongoose ODM for MongoDB and Node.js. Use for schemas, models, queries, validation, middleware, population, aggregation, and MongoDB database operations in JavaScript/TypeScript applications. |
Mongoose Skill
Mongoose odm for mongodb and node.js. use for schemas, models, queries, validation, middleware, population, aggregation, and mongodb database operations in javascript/typescript applications., generated from official documentation.
When to Use This Skill
This skill should be triggered when:
- Working with mongoose
- Asking about mongoose features or APIs
- Implementing mongoose solutions
- Debugging mongoose code
- Learning mongoose best practices
Quick Reference
Common Patterns
Pattern 1: SchemaBoolean()SchemaBoolean.cast()SchemaBoolean.checkRequired()SchemaBoolean.convertToFalseSchemaBoolean.convertToTrueSchemaBoolean.get()SchemaBoolean.prototype.$conditionalHandlersSchemaBoolean.prototype.checkRequired()SchemaBoolean.prototype.toJSONSchema()SchemaBoolean.schemaNameSchemaBoolean.set()SchemaBoolean()Parameters:path «String» options «Object» schemaOptions «Object» parentSchema «Schema» Inherits:«SchemaType»Boolean SchemaType constructor. SchemaBoolean.cast()Parameters:caster «Function» Returns:«Function» Type:«property»Get/set the function used to cast arbitrary values to booleans. Example: // Make Mongoose cast empty string '' to false. const original = mongoose.Schema.Boolean.cast(); mongoose.Schema.Boolean.cast(v => { if (v === '') { return false; } return original(v); }); // Or disable casting entirely mongoose.Schema.Boolean.cast(false); SchemaBoolean.checkRequired()Parameters:fn «Function» Returns:«Function» Type:«property»Override the function the required validator uses to check whether a boolean passes the required check. SchemaBoolean.convertToFalseType:«Set»Configure which values get casted to false. Example: const M = mongoose.model('Test', new Schema({ b: Boolean })); new M({ b: 'nay' }).b; // undefined mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); new M({ b: 'nay' }).b; // false SchemaBoolean.convertToTrueType:«Set»Configure which values get casted to true. Example: const M = mongoose.model('Test', new Schema({ b: Boolean })); new M({ b: 'affirmative' }).b; // undefined mongoose.Schema.Boolean.convertToTrue.add('affirmative'); new M({ b: 'affirmative' }).b; // true SchemaBoolean.get()Parameters:getter «Function» Returns:«this» Type:«property»Attaches a getter for all Boolean instances Example: mongoose.Schema.Boolean.get(v => v === true ? 'yes' : 'no'); const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); new Order({ isPaid: false }).isPaid; // 'no' SchemaBoolean.prototype.$conditionalHandlersType:«property»Contains the handlers for different query operators for this schema type. For example, $conditionalHandlers.$in is the function Mongoose calls to cast $in filter operators. SchemaBoolean.prototype.checkRequired()Parameters:value «Any» Returns:«Boolean» Check if the given value satisfies a required validator. For a boolean to satisfy a required validator, it must be strictly equal to true or to false. SchemaBoolean.prototype.toJSONSchema()Parameters:[options] «» [options.useBsonType=false] «» If true, return a representation with bsonType for use with MongoDB's $jsonSchema. Returns this schema type's representation in a JSON schema. SchemaBoolean.schemaNameType:«property»This schema type's name, to defend against minifiers that mangle function names. SchemaBoolean.set()Parameters:option «String» The option you'd like to set the value for value «Any» value for option Returns:«undefined,void» Type:«property»Sets a default option for all Boolean instances. Example: // Make all booleans have default of false. mongoose.Schema.Boolean.set('default', false); const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); new Order({ }).isPaid; // false
SchemaBoolean()
Pattern 2: Get/set the function used to cast arbitrary values to booleans. Example: // Make Mongoose cast empty string '' to false. const original = mongoose.Schema.Boolean.cast(); mongoose.Schema.Boolean.cast(v => { if (v === '') { return false; } return original(v); }); // Or disable casting entirely mongoose.Schema.Boolean.cast(false);
// Make Mongoose cast empty string '' to false.
const original = mongoose.Schema.Boolean.cast();
mongoose.Schema.Boolean.cast(v => {
if (v === '') {
return false;
}
return original(v);
});
// Or disable casting entirely
mongoose.Schema.Boolean.cast(false);
Pattern 3: Configure which values get casted to false. Example: const M = mongoose.model('Test', new Schema({ b: Boolean })); new M({ b: 'nay' }).b; // undefined mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); new M({ b: 'nay' }).b; // false
false
Pattern 4: Configure which values get casted to true. Example: const M = mongoose.model('Test', new Schema({ b: Boolean })); new M({ b: 'affirmative' }).b; // undefined mongoose.Schema.Boolean.convertToTrue.add('affirmative'); new M({ b: 'affirmative' }).b; // true
true
Pattern 5: Attaches a getter for all Boolean instances Example: mongoose.Schema.Boolean.get(v => v === true ? 'yes' : 'no'); const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); new Order({ isPaid: false }).isPaid; // 'no'
mongoose.Schema.Boolean.get(v => v === true ? 'yes' : 'no');
const Order = mongoose.model('Order', new Schema({ isPaid: Boolean }));
new Order({ isPaid: false }).isPaid; // 'no'
Pattern 6: Mongoose()Mongoose.prototype.Aggregate()Mongoose.prototype.CastError()Mongoose.prototype.Collection()Mongoose.prototype.Connection()Mongoose.prototype.ConnectionStatesMongoose.prototype.DateMongoose.prototype.Decimal128Mongoose.prototype.Document()Mongoose.prototype.DocumentProvider()Mongoose.prototype.Error()Mongoose.prototype.MixedMongoose.prototype.Model()Mongoose.prototype.Mongoose()Mongoose.prototype.NumberMongoose.prototype.ObjectIdMongoose.prototype.Query()Mongoose.prototype.STATESMongoose.prototype.Schema()Mongoose.prototype.SchemaType()Mongoose.prototype.SchemaTypeOptions()Mongoose.prototype.SchemaTypesMongoose.prototype.TypesMongoose.prototype.VirtualType()Mongoose.prototype.connect()Mongoose.prototype.connectionMongoose.prototype.connectionsMongoose.prototype.createConnection()Mongoose.prototype.deleteModel()Mongoose.prototype.disconnect()Mongoose.prototype.driverMongoose.prototype.get()Mongoose.prototype.isObjectIdOrHexString()Mongoose.prototype.isValidObjectId()Mongoose.prototype.model()Mongoose.prototype.modelNames()Mongoose.prototype.mongoMongoose.prototype.mqueryMongoose.prototype.now()Mongoose.prototype.overwriteMiddlewareResult()Mongoose.prototype.plugin()Mongoose.prototype.pluralize()Mongoose.prototype.sanitizeFilter()Mongoose.prototype.set()Mongoose.prototype.setDriver()Mongoose.prototype.skipMiddlewareFunction()Mongoose.prototype.startSession()Mongoose.prototype.syncIndexes()Mongoose.prototype.trusted()Mongoose.prototype.versionMongoose()Parameters:options «Object» see Mongoose#set() docs Mongoose constructor. The exports object of the mongoose module is an instance of this class. Most apps will only use this one instance. Example: const mongoose = require('mongoose'); mongoose instanceof mongoose.Mongoose; // true // Create a new Mongoose instance with its own connect(), set(), model(), etc. const m = new mongoose.Mongoose(); Mongoose.prototype.Aggregate()The Mongoose Aggregate constructor Mongoose.prototype.CastError()Parameters:type «String» The name of the type value «Any» The value that failed to cast path «String» The path a.b.c in the doc where this cast error occurred [reason] «Error» The original error that was thrown The Mongoose CastError constructor Mongoose.prototype.Collection()The Mongoose Collection constructor Mongoose.prototype.Connection()The Mongoose Connection constructor Mongoose.prototype.ConnectionStatesType:«property»Expose connection states for user-land Mongoose.prototype.DateType:«property»The Mongoose Date SchemaType. Example: const schema = new Schema({ test: Date }); schema.path('test') instanceof mongoose.Date; // true Mongoose.prototype.Decimal128Type:«property»The Mongoose Decimal128 SchemaType. Used for declaring paths in your schema that should be 128-bit decimal floating points. Do not use this to create a new Decimal128 instance, use mongoose.Types.Decimal128 instead. Example: const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 }); Mongoose.prototype.Document()The Mongoose Document constructor. Mongoose.prototype.DocumentProvider()The Mongoose DocumentProvider constructor. Mongoose users should not have to use this directly Mongoose.prototype.Error()The MongooseError constructor. Mongoose.prototype.MixedType:«property»The Mongoose Mixed SchemaType. Used for declaring paths in your schema that Mongoose's change tracking, casting, and validation should ignore. Example: const schema = new Schema({ arbitrary: mongoose.Mixed }); Mongoose.prototype.Model()The Mongoose Model constructor. Mongoose.prototype.Mongoose()The Mongoose constructor The exports of the mongoose module is an instance of this class. Example: const mongoose = require('mongoose'); const mongoose2 = new mongoose.Mongoose(); Mongoose.prototype.NumberType:«property»The Mongoose Number SchemaType. Used for declaring paths in your schema that Mongoose should cast to numbers. Example: const schema = new Schema({ num: mongoose.Number }); // Equivalent to: const schema = new Schema({ num: 'number' }); Mongoose.prototype.ObjectIdType:«property»The Mongoose ObjectId SchemaType. Used for declaring paths in your schema that should be MongoDB ObjectIds. Do not use this to create a new ObjectId instance, use mongoose.Types.ObjectId instead. Example: const childSchema = new Schema({ parentId: mongoose.ObjectId }); Mongoose.prototype.Query()The Mongoose Query constructor. Mongoose.prototype.STATESType:«property»Expose connection states for user-land Mongoose.prototype.Schema()The Mongoose Schema constructor Example: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CatSchema = new Schema(..); Mongoose.prototype.SchemaType()The Mongoose SchemaType constructor Mongoose.prototype.SchemaTypeOptions()The constructor used for schematype options Mongoose.prototype.SchemaTypesType:«property»See:Schema.SchemaTypesThe various Mongoose SchemaTypes. Note: Alias of mongoose.Schema.Types for backwards compatibility. Mongoose.prototype.TypesType:«property»The various Mongoose Types. Example: const mongoose = require('mongoose'); const array = mongoose.Types.Array; Types: Array Buffer Embedded DocumentArray Decimal128 ObjectId Map Subdocument Using this exposed access to the ObjectId type, we can construct ids on demand. const ObjectId = mongoose.Types.ObjectId; const id1 = new ObjectId; Mongoose.prototype.VirtualType()The Mongoose VirtualType constructor Mongoose.prototype.connect()Parameters:uri «String» mongodb URI to connect to [options] «Object» passed down to the MongoDB driver's connect() function, except for 4 mongoose-specific options explained below. [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection. [options.bufferTimeoutMS=10000] «Number» Mongoose specific option. If bufferCommands is true, Mongoose will throw an error after bufferTimeoutMS if the operation is still buffered. [options.dbName] «String» The name of the database we want to use. If not provided, use database name from connection string. [options.user] «String» username for authentication, equivalent to options.auth.user. Maintained for backwards compatibility. [options.pass] «String» password for authentication, equivalent to options.auth.password. Maintained for backwards compatibility. [options.maxPoolSize=100] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. [options.minPoolSize=0] «Number» The minimum number of sockets the MongoDB driver will keep open for this connection. [options.serverSelectionTimeoutMS] «Number» If useUnifiedTopology = true, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for serverSelectionTimeoutMS milliseconds before erroring out. If not set, the MongoDB driver defaults to using 30000 (30 seconds). [options.heartbeatFrequencyMS] «Number» If useUnifiedTopology = true, the MongoDB driver sends a heartbeat every heartbeatFrequencyMS to check on the status of the connection. A heartbeat is subject to serverSelectionTimeoutMS, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a 'disconnected' event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits 'disconnected'. We recommend you do not set this setting below 1000, too many heartbeats can lead to performance degradation. [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. [options.promiseLibrary] «Class» Sets the underlying driver's promise library. [options.socketTimeoutMS=0] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity after initial connection. A socket may be inactive because of either no activity or a long-running operation. socketTimeoutMS defaults to 0, which means Node.js will not time out the socket due to inactivity. This option is passed to Node.js socket#setTimeout() function after the MongoDB driver successfully completes. [options.family=0] «Number» Passed transparently to Node.js' dns.lookup() function. May be either 0, 4, or 6. 4 means use IPv4 only, 6 means use IPv6 only, 0 means try both. [options.autoCreate=false] «Boolean» Set to true to make Mongoose automatically call createCollection() on every model created on this connection. [callback] «Function» Returns:«Promise» resolves to this if connection succeededSee:Mongoose#createConnectionOpens the default mongoose connection. Example: mongoose.connect('mongodb://user:pass@127.0.0.1:port/database'); // replica sets const uri = 'mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/mydatabase'; mongoose.connect(uri); // with options mongoose.connect(uri, options); // Using await throws "MongooseServerSelectionError: Server selection timed out after 30000 ms" // if Mongoose can't connect. const uri = 'mongodb://nonexistent.domain:27000'; await mongoose.connect(uri); Mongoose.prototype.connectionType:«Connection»The Mongoose module's default connection. Equivalent to mongoose.connections[0], see connections. Example: const mongoose = require('mongoose'); mongoose.connect(...); mongoose.connection.on('error', cb); This is the connection used by default for every model created using mongoose.model. To create a new connection, use createConnection(). Mongoose.prototype.connectionsType:«Array»An array containing all connections associated with this Mongoose instance. By default, there is 1 connection. Calling createConnection() adds a connection to this array. Example: const mongoose = require('mongoose'); mongoose.connections.length; // 1, just the default connection mongoose.connections[0] === mongoose.connection; // true mongoose.createConnection('mongodb://127.0.0.1:27017/test'); mongoose.connections.length; // 2 Mongoose.prototype.createConnection()Parameters:uri «String» mongodb URI to connect to [options] «Object» passed down to the MongoDB driver's connect() function, except for 4 mongoose-specific options explained below. [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection. [options.dbName] «String» The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. [options.user] «String» username for authentication, equivalent to options.auth.user. Maintained for backwards compatibility. [options.pass] «String» password for authentication, equivalent to options.auth.password. Maintained for backwards compatibility. [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. [options.promiseLibrary] «Class» Sets the underlying driver's promise library. [options.maxPoolSize=5] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. [options.minPoolSize=1] «Number» The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. [options.socketTimeoutMS=0] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity after initial connection. Defaults to 0, which means Node.js will not time out the socket due to inactivity. A socket may be inactive because of either no activity or a long-running operation. This option is passed to Node.js socket#setTimeout() function after the MongoDB driver successfully completes. [options.family=0] «Number» Passed transparently to Node.js' dns.lookup() function. May be either 0, 4, or 6. 4 means use IPv4 only, 6 means use IPv6 only, 0 means try both. Returns:«Connection» the created Connection object. Connections are not thenable, so you can't do await mongoose.createConnection(). To await use mongoose.createConnection(uri).asPromise() instead.Creates a Connection instance. Each connection instance maps to a single database. This method is helpful when managing multiple db connections. Options passed take precedence over options included in connection strings. Example: // with mongodb:// URI db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port/database'); // and options const opts = { db: { native_parser: true }} db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port/database', opts); // replica sets db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/database'); // and options const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/database', opts); // initialize now, connect later db = mongoose.createConnection(); await db.openUri('mongodb://127.0.0.1:27017/database'); Mongoose.prototype.deleteModel()Parameters:name «String|RegExp» if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. Returns:«Mongoose» thisRemoves the model named name from the default connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors. Equivalent to mongoose.connection.deleteModel(name). Example: mongoose.model('User', new Schema({ name: String })); console.log(mongoose.model('User')); // Model object mongoose.deleteModel('User'); console.log(mongoose.model('User')); // undefined // Usually useful in a Mocha afterEach() hook afterEach(function() { mongoose.deleteModel(/.+/); // Delete every model }); Mongoose.prototype.disconnect()Returns:«Promise» resolves when all connections are closed, or rejects with the first error that occurred.Runs .close() on all connections in parallel. Mongoose.prototype.driverDEPRECATEDType:«property»Object with get() and set() containing the underlying driver this Mongoose instance uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions like find(). Mongoose.prototype.get()Parameters:key «String» Gets mongoose options Example: mongoose.get('test') // returns the 'test' value Mongoose.prototype.isObjectIdOrHexString()Parameters:v «Any» Returns true if the given value is a Mongoose ObjectId (using instanceof) or if the given value is a 24 character hex string, which is the most commonly used string representation of an ObjectId. This function is similar to isValidObjectId(), but considerably more strict, because isValidObjectId() will return true for any value that Mongoose can convert to an ObjectId. That includes Mongoose documents, any string of length 12, and any number. isObjectIdOrHexString() returns true only for ObjectId instances or 24 character hex strings, and will return false for numbers, documents, and strings of length 12. Example: mongoose.isObjectIdOrHexString(new mongoose.Types.ObjectId()); // true mongoose.isObjectIdOrHexString('62261a65d66c6be0a63c051f'); // true mongoose.isObjectIdOrHexString('0123456789ab'); // false mongoose.isObjectIdOrHexString(6); // false mongoose.isObjectIdOrHexString(new User({ name: 'test' })); // false mongoose.isObjectIdOrHexString({ test: 42 }); // false Mongoose.prototype.isValidObjectId()Parameters:v «Any» Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise. Example: mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true mongoose.isValidObjectId('0123456789ab'); // true mongoose.isValidObjectId(6); // true mongoose.isValidObjectId(new User({ name: 'test' })); // true mongoose.isValidObjectId({ test: 42 }); // false Mongoose.prototype.model()Parameters:name «String|Function» model name or class extending Model [schema] «Schema» the schema to use. [collection] «String» name (optional, inferred from model name) [options] «Object» [options.overwriteModels=false] «Boolean» If true, overwrite existing models with the same name to avoid OverwriteModelError Returns:«Model» The model associated with name. Mongoose will create the model if it doesn't already exist.Defines a model or retrieves it. Models defined on the mongoose instance are available to all connection created by the same mongoose instance. If you call mongoose.model() with twice the same name but a different schema, you will get an OverwriteModelError. If you call mongoose.model() with the same name and same schema, you'll get the same schema back. Example: const mongoose = require('mongoose'); // define an Actor model with this mongoose instance const schema = new Schema({ name: String }); mongoose.model('Actor', schema); // create a new connection const conn = mongoose.createConnection(..); // create Actor model const Actor = conn.model('Actor', schema); conn.model('Actor') === Actor; // true conn.model('Actor', schema) === Actor; // true, same schema conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name // This throws an OverwriteModelError because the schema is different. conn.model('Actor', new Schema({ name: String })); When no collection argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use mongoose.pluralize(), or set your schemas collection name option. Example: const schema = new Schema({ name: String }, { collection: 'actor' }); // or schema.set('collection', 'actor'); // or const collectionName = 'actor'; const M = mongoose.model('Actor', schema, collectionName); Mongoose.prototype.modelNames()Returns:«Array» Returns an array of model names created on this instance of Mongoose. Note: Does not include names of models created using connection.model(). Mongoose.prototype.mongoType:«property»The node-mongodb-native driver Mongoose uses. Mongoose.prototype.mqueryType:«property»The mquery query builder Mongoose uses. Mongoose.prototype.now()Mongoose uses this function to get the current time when setting timestamps. You may stub out this function using a tool like Sinon for testing. Mongoose.prototype.overwriteMiddlewareResult()Parameters:result «any» Use this function in post() middleware to replace the result Example: schema.post('find', function(res) { // Normally you have to modify res in place. But with // overwriteMiddlewarResult(), you can make find() return a // completely different value. return mongoose.overwriteMiddlewareResult(res.filter(doc => !doc.isDeleted)); }); Mongoose.prototype.plugin()Parameters:fn «Function» plugin callback [opts] «Object» optional options Returns:«Mongoose» thisSee:pluginsDeclares a global plugin executed on all Schemas. Equivalent to calling .plugin(fn) on each Schema you create. Mongoose.prototype.pluralize()Parameters:[fn] «Function|null» overwrites the function used to pluralize collection names Returns:«Function,null» the current function used to pluralize collection names, defaults to the legacy function from mongoose-legacy-pluralize.Getter/setter around function for pluralizing collection names. Mongoose.prototype.sanitizeFilter()Parameters:filter «Object» Sanitizes query filters against query selector injection attacks by wrapping any nested objects that have a property whose name starts with $ in a $eq. const obj = { username: 'val', pwd: { $ne: null } }; sanitizeFilter(obj); obj; // { username: 'val', pwd: { $eq: { $ne: null } } }); Mongoose.prototype.set()Parameters:key «String|Object» The name of the option or a object of multiple key-value pairs value «String|Function|Boolean» The value of the option, unused if "key" is a object Sets mongoose options key can be used a object to set multiple options at once. If a error gets thrown for one option, other options will still be evaluated. Example: mongoose.set('test', value) // sets the 'test' option to value mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments mongoose.set({ debug: true, autoIndex: false }); // set multiple options at once Currently supported options are: allowDiskUse: Set to true to set allowDiskUse to true to all aggregation operations by default. applyPluginsToChildSchemas: true by default. Set to false to skip applying global plugins to child schemas applyPluginsToDiscriminators: false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema. autoCreate: Set to true to make Mongoose call Model.createCollection() automatically when you create a model with mongoose.model() or conn.model(). This is useful for testing transactions, change streams, and other features that require the collection to exist. autoIndex: true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance. bufferCommands: enable/disable mongoose's buffering mechanism for all connections and models bufferTimeoutMS: If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before throwing an error. If not specified, Mongoose will use 10000 (10 seconds). cloneSchemas: false by default. Set to true to clone() all schemas before compiling into a model. debug: If true, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arguments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')}). id: If true, adds a id virtual to all schemas unless overwritten on a per-schema basis. timestamps.createdAt.immutable: true by default. If false, it will change the createdAt field to be immutable: false which means you can update the createdAt maxTimeMS: If set, attaches maxTimeMS to every query objectIdGetter: true by default. Mongoose adds a getter to MongoDB ObjectId's called _id that returns this for convenience with populate. Set this to false to remove the getter. overwriteModels: Set to true to default to overwriting models with the same name when calling mongoose.model(), as opposed to throwing an OverwriteModelError. returnOriginal: If false, changes the default returnOriginal option to findOneAndUpdate(), findByIdAndUpdate, and findOneAndReplace() to false. This is equivalent to setting the new option to true for findOneAndX() calls by default. Read our findOneAndUpdate() tutorial for more information. runValidators: false by default. Set to true to enable update validators for all validators by default. sanitizeFilter: false by default. Set to true to enable the sanitization of the query filters against query selector injection attacks by wrapping any nested objects that have a property whose name starts with $ in a $eq. selectPopulatedPaths: true by default. Set to false to opt out of Mongoose adding all fields that you populate() to your select(). The schema-level option selectPopulatedPaths overwrites this one. strict: true by default, may be false, true, or 'throw'. Sets the default strict mode for schemas. strictQuery: false by default. May be false, true, or 'throw'. Sets the default strictQuery mode for schemas. toJSON: { transform: true, flattenDecimals: true } by default. Overwrites default objects to toJSON(), for determining how Mongoose documents get serialized by JSON.stringify() toObject: { transform: true, flattenDecimals: true } by default. Overwrites default objects to toObject() Mongoose.prototype.setDriver()Overwrites the current driver used by this Mongoose instance. A driver is a Mongoose-specific interface that defines functions like find(). Mongoose.prototype.skipMiddlewareFunction()Parameters:result «any» Use this function in pre() middleware to skip calling the wrapped function. Example: schema.pre('save', function() { // Will skip executing save(), but will execute post hooks as if // save() had executed with the result { matchedCount: 0 } return mongoose.skipMiddlewareFunction({ matchedCount: 0 }); }); Mongoose.prototype.startSession()Parameters:[options] «Object» see the mongodb driver options [options.causalConsistency=true] «Boolean» set to false to disable causal consistency [callback] «Function» Returns:«PromisesanitizeFilter() did not add $eq around $type. obj; // { username: 'val', pwd: { $type: 'string', $eq: 'my secret' } }); Mongoose.prototype.versionType:«property»The Mongoose version Example: console.log(mongoose.version); // '5.x.x'
Mongoose()
Pattern 7: Mongoose constructor. The exports object of the mongoose module is an instance of this class. Most apps will only use this one instance. Example: const mongoose = require('mongoose'); mongoose instanceof mongoose.Mongoose; // true // Create a new Mongoose instance with its own connect(), set(), model(), etc. const m = new mongoose.Mongoose();
mongoose
Pattern 8: The Mongoose Date SchemaType. Example: const schema = new Schema({ test: Date }); schema.path('test') instanceof mongoose.Date; // true
const schema = new Schema({ test: Date });
schema.path('test') instanceof mongoose.Date; // true
Example Code Patterns
Example 1 (typescript):
import { Document, Schema, model, connect } from 'mongoose';
interface User extends Document {
name: string;
email: string;
avatar?: string;
}
Example 2 (javascript):
mongoose.connect('mongodb://127.0.0.1:27017/myapp');
Example 3 (javascript):
mongoose.connect('mongodb://username:password@host:port/database?options...');
Example 4 (javascript):
const doc = await MyModel.findOne();
doc instanceof MyModel; // true
doc instanceof mongoose.Model; // true
doc instanceof mongoose.Document; // true
Example 5 (javascript):
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
Reference Files
This skill includes comprehensive documentation in references/:
- aggregation.md - Aggregation documentation
- api_reference.md - Api Reference documentation
- getting_started.md - Getting Started documentation
- middleware.md - Middleware documentation
- models.md - Models documentation
- other.md - Other documentation
- population.md - Population documentation
- queries.md - Queries documentation
- schemas.md - Schemas documentation
- validation.md - Validation documentation
Use view to read specific reference files when detailed information is needed.
Working with This Skill
For Beginners
Start with the getting_started or tutorials reference files for foundational concepts.
For Specific Features
Use the appropriate category reference file (api, guides, etc.) for detailed information.
For Code Examples
The quick reference section above contains common patterns extracted from the official docs.
Resources
references/
Organized documentation extracted from official sources. These files contain:
- Detailed explanations
- Code examples with language annotations
- Links to original documentation
- Table of contents for quick navigation
scripts/
Add helper scripts here for common automation tasks.
assets/
Add templates, boilerplate, or example projects here.
Notes
- This skill was automatically generated from official documentation
- Reference files preserve the structure and examples from source docs
- Code examples include language detection for better syntax highlighting
- Quick reference patterns are extracted from common usage examples in the docs
Updating
To refresh this skill with updated documentation:
- Re-run the scraper with the same configuration
- The skill will be rebuilt with the latest information