### Install Mongoose Source: https://mongoosejs.com/docs/index.html Install Mongoose using npm. Ensure Node.js and MongoDB are installed first. ```bash npm install mongoose ``` -------------------------------- ### Install mongodb-client-encryption Package Source: https://mongoosejs.com/docs/field-level-encryption.html Install the official MongoDB package for setting up encryption keys. This is a prerequisite for manual FLE setup in Mongoose. ```bash npm install mongodb-client-encryption ``` -------------------------------- ### Start, Commit, and Observe Transaction Source: https://mongoosejs.com/docs/transactions.html Demonstrates how to start a transaction, perform operations within it, and observe visibility changes before and after committing. Requires a Mongoose model and database connection. ```javascript const Customer = db.model('Customer', new Schema({ name: String })); let session = null; return Customer.createCollection(). then(() => db.startSession()). then(_session => { session = _session; // Start a transaction session.startTransaction(); // This `create()` is part of the transaction because of the `session` // option. return Customer.create([{ name: 'Test' }], { session: session }); }). // Transactions execute in isolation, so unless you pass a `session` // to `findOne()` you won't see the document until the transaction // is committed. then(() => Customer.findOne({ name: 'Test' })). then(doc => assert.ok(!doc)). // This `findOne()` will return the doc, because passing the `session` // means this `findOne()` will run as part of the transaction. then(() => Customer.findOne({ name: 'Test' }).session(session)). then(doc => assert.ok(doc)). // Once the transaction is committed, the write operation becomes // visible outside of the transaction. then(() => session.commitTransaction()). then(() => Customer.findOne({ name: 'Test' })). then(doc => assert.ok(doc)). then(() => session.endSession()); ``` -------------------------------- ### Full Example of `loadClass()` with TypeScript Source: https://mongoosejs.com/docs/typescript/statics-and-methods.html A complete example demonstrating `loadClass()` with Mongoose and TypeScript, including imports, type definitions, and model creation. ```typescript import { Model, Schema, model, HydratedDocument } from 'mongoose'; interface RawDocType { property1: string; } class MyClass { myMethod(this: MyCombinedDocument) { return this.property1; } static myStatic(this: MyCombinedModel) { return 42; } get myVirtual() { const self = this as MyCombinedDocument; return `Hello ${self.property1}`; } } const schema = new Schema({ property1: String }); schema.loadClass(MyClass); type MyCombinedModel = Model< RawDocType, {}, Pick, Pick > & Pick; type MyCombinedDocument = HydratedDocument< RawDocType, Pick, {}, Pick >; const MyModel = model( 'MyClass', schema ); const doc = new MyModel({ property1: 'world' }); doc.myMethod(); MyModel.myStatic(); console.log(doc.myVirtual); ``` -------------------------------- ### Connection String Options Example Source: https://mongoosejs.com/docs/connections.html Demonstrates setting driver options directly in the connection string URI, such as socket timeout. ```javascript mongoose.connect('mongodb://127.0.0.1:27017/test?socketTimeoutMS=1000&bufferCommands=false&authSource=otherdb'); ``` -------------------------------- ### Mongoose findOneAndDelete Examples Source: https://mongoosejs.com/docs/api/query.html Demonstrates various ways to call the `findOneAndDelete` method on a Mongoose model. These examples show how to include conditions and options, or call the method without arguments. ```javascript A.where().findOneAndDelete(conditions, options) // return Query ``` ```javascript A.where().findOneAndDelete(conditions) // returns Query ``` ```javascript A.where().findOneAndDelete() // returns Query ``` -------------------------------- ### Multi-field Sort Output Example Source: https://mongoosejs.com/docs/queries.html Example output demonstrating how MongoDB sorts by age first, and then by weight when ages are equal. ```json [ { _id: new ObjectId('63a335a6b9b6a7bfc186cb37'), age: 0, name: 'Test2', weight: 67, __v: 0 }, { _id: new ObjectId('63a335a6b9b6a7bfc186cb35'), age: 1, name: 'Test1', weight: 99, __v: 0 }, { _id: new ObjectId('63a335a6b9b6a7bfc186cb39'), age: 1, name: 'Test3', weight: 73, __v: 0 }, { _id: new ObjectId('63a335a6b9b6a7bfc186cb33'), age: 2, name: 'Test0', weight: 65, __v: 0 }, { _id: new ObjectId('63a335a6b9b6a7bfc186cb3b'), age: 2, name: 'Test4', weight: 62, __v: 0 } ]; ``` -------------------------------- ### Get and Set Schema Options with get/set Source: https://mongoosejs.com/docs/api/schema.html Retrieve schema options using `get()` and modify them using `set()`. This is useful for inspecting or changing schema behaviors like strict mode. ```javascript schema.get('strict'); // true schema.set('strict', false); schema.get('strict'); // false ``` -------------------------------- ### Creating a Band Document with Map Data Source: https://mongoosejs.com/docs/populate.html Example of creating a 'Band' document and populating its 'members' map with ObjectIds. ```javascript const person1 = new Person({ name: 'Vince Neil' }); const person2 = new Person({ name: 'Mick Mars' }); const band = new Band({ name: 'Motley Crue', members: { singer: person1._id, guitarist: person2._id } }); ``` -------------------------------- ### Model.startSession() Source: https://mongoosejs.com/docs/api/model.html Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions. ```APIDOC ## Model.startSession() ### Description Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions. Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`. ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body * `[options]` (object) - See the mongodb driver options. * `[options.causalConsistency=true]` (boolean) - Set to false to disable causal consistency. ### Returns * «Promise» - Promise that resolves to a MongoDB driver `ClientSession`. ### Requirements _Requires MongoDB >= 3.6.0._ ### Middleware This function does not trigger any middleware. ### Example: ```javascript const session = await Person.startSession(); let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); await doc.deleteOne(); // `doc` will always be null, even if reading from a replica set // secondary. Without causal consistency, it is possible to // get a doc back from the below query if the query reads from a // secondary that is experiencing replication lag. doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); ``` ``` -------------------------------- ### Document Middleware Example for findOneAndUpdate Source: https://mongoosejs.com/docs/middleware.html This example demonstrates how document middleware for 'findOneAndUpdate' is executed on the parent document but not on subdocuments. Document middleware functions have `this` refer to the document. ```javascript const childSchema = new mongoose.Schema({ name: String }); const mainSchema = new mongoose.Schema({ child: [childSchema] }); mainSchema.pre('findOneAndUpdate', function() { console.log('Middleware on parent document'); // Will be executed }); childSchema.pre('findOneAndUpdate', function() { console.log('Middleware on subdocument'); // Will not be executed }); ``` -------------------------------- ### Customize Version Key Source: https://mongoosejs.com/docs/guide.html Configure a custom `versionKey` other than the default `__v`. This example demonstrates setting `_somethingElse` as the version key. ```javascript new Schema({ /* ... */ }, { versionKey: '_somethingElse' }) const Thing = mongoose.model('Thing', schema); const thing = new Thing({ name: 'mongoose v3' }); thing.save(); // { _somethingElse: 0, name: 'mongoose v3' } ``` -------------------------------- ### Synchronous Post Middleware Examples Source: https://mongoosejs.com/docs/middleware.html Examples of synchronous post middleware for different Mongoose events like 'init', 'validate', 'save', and 'deleteOne'. These hooks execute immediately after the event. ```javascript schema.post('init', function(doc) { console.log('%s has been initialized from the db', doc._id); }); schema.post('validate', function(doc) { console.log('%s has been validated (but not saved yet)', doc._id); }); schema.post('save', function(doc) { console.log('%s has been saved', doc._id); }); schema.post('deleteOne', function(doc) { console.log('%s has been deleted', doc._id); }); ``` -------------------------------- ### Configure Default Version Key Source: https://mongoosejs.com/docs/guide.html Set the default `versionKey` to `__v` for new documents. This example shows creating a schema and saving a document. ```javascript const schema = new Schema({ name: 'string' }); const Thing = mongoose.model('Thing', schema); const thing = new Thing({ name: 'mongoose v3' }); await thing.save(); // { __v: 0, name: 'mongoose v3' } ``` -------------------------------- ### Mongoose findOneAndReplace Examples Source: https://mongoosejs.com/docs/api/query.html Illustrates different ways to use the `findOneAndReplace` method in Mongoose. Examples include providing filter, replacement, and options, or calling the method with fewer arguments. ```javascript A.where().findOneAndReplace(filter, replacement, options); // return Query ``` ```javascript A.where().findOneAndReplace(filter); // returns Query ``` ```javascript A.where().findOneAndReplace(); // returns Query ``` -------------------------------- ### Mongoose Types Utility Example Source: https://mongoosejs.com/docs/api.html Shows how to access Mongoose types like Array. ```javascript const mongoose = require('mongoose'); const array = mongoose.Types.Array; ``` -------------------------------- ### Query.prototype.getOptions() Source: https://mongoosejs.com/docs/api/query.html Gets query options, including those set by methods like `limit()` and `setOptions()`. ```APIDOC ## Query.prototype.getOptions() ### Description Gets query options. ### Returns * `object` - The options. ### Request Example ```javascript const query = new Query(); query.limit(10); query.setOptions({ maxTimeMS: 1000 }); query.getOptions(); // { limit: 10, maxTimeMS: 1000 } ``` ``` -------------------------------- ### Connection.prototype.get() Source: https://mongoosejs.com/docs/api/connection.html Gets the value of the specified option key. Equivalent to `conn.options[key]`. ```APIDOC ## Connection.prototype.get() ### Description Gets the value of the specified option key. Equivalent to `conn.options[key]`. ### Method `get` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * `key` (string) - Required - The key of the option to retrieve. ### Request Example ```javascript conn.get('test'); // returns the 'test' value ``` ### Response #### Success Response * Returns the value of the specified option. #### Response Example (No specific example provided in source) ``` -------------------------------- ### Mongoose.prototype.startSession Source: https://mongoosejs.com/docs/api/mongoose.html Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions. Sessions are scoped to a connection. ```APIDOC ## Mongoose.prototype.startSession ### Description Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions. Sessions are scoped to a connection, so calling `mongoose.startSession()` starts a session on the default mongoose connection. Requires MongoDB version 3.6.0 or higher. ### Method N/A (This is a method on the Mongoose instance, not a direct HTTP endpoint.) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **options** (object) - Optional - See the mongodb driver options. - **options.causalConsistency** (boolean) - Optional - Set to `false` to disable causal consistency. Defaults to `true`. ### Request Example ```javascript // Example of starting a session with default options const session = await mongoose.startSession(); // Example of starting a session with causal consistency disabled const sessionNoCausal = await mongoose.startSession({ causalConsistency: false }); ``` ### Response #### Success Response (Promise) - **Promise** - Resolves to a MongoDB driver `ClientSession` object. #### Response Example ```javascript // Assuming session is a resolved ClientSession object console.log(session); ``` ``` -------------------------------- ### Start a Mongoose Session Source: https://mongoosejs.com/docs/transactions.html Initiate a session for transactions using either the default Mongoose connection or a custom connection. ```javascript // Using Mongoose's default connection const session = await mongoose.startSession(); // Using custom connection const db = await mongoose.createConnection(mongodbUri).asPromise(); const session = await db.startSession(); ``` -------------------------------- ### Get Mongoose Version in Node.js Source: https://mongoosejs.com/docs/check-version.html Print the `mongoose.version` property in your Node.js application to get the installed version. This is the recommended method for accuracy. ```javascript const mongoose = require('mongoose'); console.log(mongoose.version); // '7.x.x' ``` -------------------------------- ### Execute Aggregation with Explain Source: https://mongoosejs.com/docs/api/aggregate.html Use to get detailed information about the execution plan of an aggregation query. This is helpful for performance analysis. ```javascript Model.aggregate(..).explain() ``` -------------------------------- ### Express Route Using Lean for GET Request Source: https://mongoosejs.com/docs/tutorials/lean.html Use lean() for GET requests when you don't need Mongoose document methods, virtuals, or getters. This example retrieves a person document and sends it as JSON. ```javascript // As long as you don't need any of the Person model's virtuals or getters, // you can use `lean()`. app.get('/person/:id', function(req, res) { Person.findOne({ _id: req.params.id }).lean(). then(person => res.json({ person })). catch(error => res.json({ error: error.message })); }); ``` -------------------------------- ### Getting Query Options with getOptions() Source: https://mongoosejs.com/docs/api/query.html getOptions() retrieves all query options, including those set by methods like limit() and setOptions(). ```javascript const query = new Query(); query.limit(10); query.setOptions({ maxTimeMS: 1000 }); query.getOptions(); // { limit: 10, maxTimeMS: 1000 } ``` -------------------------------- ### Connect to MongoDB and check ready state Source: https://mongoosejs.com/docs/api/connection.html Use `createConnection()` to establish a connection and `asPromise()` to get a promise that resolves when the connection is successful. Check `readyState` to confirm connection status. ```javascript const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/test'). asPromise(); conn.readyState; // 1, means Mongoose is connected ``` -------------------------------- ### Accessing Virtuals on Model Type Source: https://mongoosejs.com/docs/typescript/virtuals.html Mongoose adds virtuals to the model type, allowing them to be accessed on model instances. This example shows how to get the hydrated document type. ```typescript const UserModel = model('User', schema); const user = new UserModel({ firstName: 'foo' }); // Works user.fullName; // Here's how to get the hydrated document type type UserDocument = ReturnType<(typeof UserModel)['hydrate']>; ``` -------------------------------- ### Query Documents with Filter Source: https://mongoosejs.com/docs/index.html Filter documents based on specific criteria using Mongoose's support for MongoDB's query syntax. This example finds kittens whose names start with 'fluff'. ```javascript await Kitten.find({ name: /^fluff/ }); ``` -------------------------------- ### Create Sample Stories Source: https://mongoosejs.com/docs/populate.html Creates two sample 'Story' documents with arrays of fans for demonstrating populate limit options. ```javascript await Story.create([ { title: 'Casino Royale', fans: [1, 2, 3, 4, 5, 6, 7, 8] }, { title: 'Live and Let Die', fans: [9, 10] } ]); ``` -------------------------------- ### Document.prototype.$init() Source: https://mongoosejs.com/docs/api/document.html Alias for `.init`. ```APIDOC ## `Document.prototype.$init()` ### Description Alias for `.init`. ``` -------------------------------- ### Customizing Current Time Function for Timestamps Source: https://mongoosejs.com/docs/guide.html This example shows how to override the default function Mongoose uses to get the current time for timestamps. It configures the schema to use Unix time (seconds since epoch) instead of JavaScript Date objects. ```javascript const schema = Schema({ createdAt: Number, updatedAt: Number, name: String }, { // Make Mongoose use Unix time (seconds since Jan 1, 1970) timestamps: { currentTime: () => Math.floor(Date.now() / 1000) } }); ``` -------------------------------- ### SchemaType.checkRequired() Source: https://mongoosejs.com/docs/api/schematype.html This static method allows getting or setting the `checkRequired` function for a schema type. This function determines how the `required` validator checks if a value passes. It can be overridden to customize the validation logic, for example, to allow empty strings to pass the `required` check. ```APIDOC ## SchemaType.checkRequired() ### Description Set & Get the `checkRequired` function. Override the function the required validator uses to check whether a value passes the `required` check. Override this on the individual SchemaType. ### Parameters * `[fn]` (Function) If set, will overwrite the current set function ### Returns * (Function) The input `fn` or the already set function ### Example ```javascript // Use this to allow empty strings to pass the `required` validator mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); ``` ``` -------------------------------- ### Connect to a Replica Set Source: https://mongoosejs.com/docs/connections.html To connect to a replica set, provide a comma-delimited list of hosts. This example shows the general format for connecting to multiple hosts in a replica set. ```javascript mongoose.connect('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]' [, options]); ``` ```javascript mongoose.connect('mongodb://user:pw@host1.com:27017,host2.com:27017,host3.com:27017/testdb'); ``` -------------------------------- ### Lean Populate with Virtual Population Source: https://mongoosejs.com/docs/tutorials/lean.html This example illustrates that lean() also works with virtual populate, ensuring lean results for both the main document and its virtual fields. This is useful for optimizing data retrieval when using virtuals. Models and data must be set up beforehand. ```javascript const groupSchema = new mongoose.Schema({ name: String }); groupSchema.virtual('members', { ref: 'Person', localField: '_id', foreignField: 'groupId' }); const Group = mongoose.model('Group', groupSchema); const Person = mongoose.model('Person', new mongoose.Schema({ name: String, groupId: mongoose.ObjectId })); // Initialize data const g = await Group.create({ name: 'DS9 Characters' }); await Person.create([ { name: 'Benjamin Sisko', groupId: g._id }, { name: 'Kira Nerys', groupId: g._id } ]); // Execute a lean query const group = await Group.findOne().lean().populate({ path: 'members', options: { sort: { name: 1 } } }); group.members[0].name; // 'Benjamin Sisko' group.members[1].name; // 'Kira Nerys' // Both the `group` and the populated `members` are lean. group instanceof mongoose.Document; // false group.members[0] instanceof mongoose.Document; // false group.members[1] instanceof mongoose.Document; // false ``` -------------------------------- ### Get Nested Properties with get() Source: https://mongoosejs.com/docs/documents.html Use the get() function to safely read deeply nested properties, similar to JavaScript's optional chaining operator. It handles nullish values gracefully. ```javascript const doc2 = new TestModel(); doc2.get('subdoc.subdocLevel2.name'); // undefined doc2.subdoc?.subdocLevel2?.name; // undefined doc2.set('subdoc.subdocLevel2.name', 'Will Smith'); doc2.get('subdoc.subdocLevel2.name'); // 'Will Smith' ``` -------------------------------- ### Synchronous Init Hooks Example Source: https://mongoosejs.com/docs/middleware.html Demonstrates using pre and post init hooks for synchronous operations. The pre hook receives a plain object, while the post hook receives a Mongoose document. ```javascript const schema = new Schema({ title: String, loadedAt: Date }); schema.pre('init', pojo => { assert.equal(pojo.constructor.name, 'Object'); // Plain object before init }); const now = new Date(); schema.post('init', doc => { assert.ok(doc instanceof mongoose.Document); // Mongoose doc after init doc.loadedAt = now; }); const Test = db.model('Test', schema); return Test.create({ title: 'Casino Royale' }). then(doc => Test.findById(doc)). then(doc => assert.equal(doc.loadedAt.valueOf(), now.valueOf())); ``` -------------------------------- ### GeoJSON Point Example Source: https://mongoosejs.com/docs/geojson.html An example of a GeoJSON Point object representing a location. Note that longitude comes before latitude. ```json { "type" : "Point", "coordinates" : [ -122.5, 37.7 ] } ``` -------------------------------- ### Instantiating and Using a Mongoose Query Source: https://mongoosejs.com/docs/api/query.html Demonstrates how to use Model functions to create a Query instance, set options, specify conditions, and execute the query. It also shows how to instantiate a Query directly, though this is for advanced users. ```javascript const query = MyModel.find(); // `query` is an instance of `Query` query.setOptions({ lean : true }); query.collection(MyModel.collection); query.where('age').gte(21).exec(callback); // You can instantiate a query directly. There is no need to do // this unless you're an advanced user with a very good reason to. const query = new mongoose.Query(); ``` -------------------------------- ### Connection Options Object Example Source: https://mongoosejs.com/docs/connections.html Shows how to set driver options using a separate options object, which is preferred for clarity and managing Mongoose-specific settings. ```javascript // The above is equivalent to: mongoose.connect('mongodb://127.0.0.1:27017/test', { socketTimeoutMS: 1000 // Note that mongoose will **not** pull `bufferCommands` from the query string }); ``` -------------------------------- ### GeoJSON Polygon Example Source: https://mongoosejs.com/docs/geojson.html An example of a GeoJSON Polygon object representing a rectangular area. Polygons use triple-nested arrays for coordinates. ```json { "type": "Polygon", "coordinates": [[ [-109, 41], [-102, 41], [-102, 37], [-109, 37], [-109, 41] ]] } ``` -------------------------------- ### Creating and Inspecting Discriminator Instances Source: https://mongoosejs.com/docs/discriminators.html Demonstrates creating instances of different discriminator models and inspecting their `__t` property to verify the discriminator key. ```javascript const event1 = new Event({ time: Date.now() }); const event2 = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' }); const event3 = new SignedUpEvent({ time: Date.now(), user: 'testuser' }); assert.ok(!event1.__t); assert.equal(event2.__t, 'ClickedLink'); assert.equal(event3.__t, 'SignedUp'); ``` -------------------------------- ### ES6 Class Setter Example Source: https://mongoosejs.com/docs/tutorials/getters-setters.html This example shows a standard ES6 class setter. Note that it does not transform the value and the property remains undefined after setting. ```javascript class User { // This won't convert the email to lowercase! That's because `email` // is just a setter, the actual `email` property doesn't store any data. // also eslint will warn about using "return" on a setter set email(v) { // eslint-disable-next-line no-setter-return return v.toLowerCase(); } } const user = new User(); user.email = 'TEST@gmail.com'; user.email; // undefined ``` -------------------------------- ### Populate Multiple Paths in Pre-Find Middleware (Incorrect) Source: https://mongoosejs.com/docs/populate.html This example shows an incorrect way to populate multiple paths in middleware, which can lead to infinite recursion. ```javascript const userSchema = new Schema({ email: String, password: String, followers: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }], following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] }); userSchema.pre('find', function(next) { this.populate('followers following'); next(); }); const User = mongoose.model('User', userSchema); ``` -------------------------------- ### Instantiate Mongoose Source: https://mongoosejs.com/docs/api/mongoose.html Demonstrates how to instantiate the Mongoose constructor. The default export of the mongoose module is already an instance, but you can create new ones for isolated configurations. ```javascript 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(); ``` -------------------------------- ### Schema.prototype.alias() Source: https://mongoosejs.com/docs/api/schema.html Adds an alias for a given path. Getting or setting the alias is equivalent to getting or setting the original path. This is useful for providing more user-friendly names for schema fields. ```APIDOC ## Schema.prototype.alias() ### Description Add an alias for `path`. This means getting or setting the `alias` is equivalent to getting or setting the `path`. ### Method `Schema.prototype.alias(path, alias)` ### Parameters #### Parameters - **path** (string) - real path to alias - **alias** (string|Array[string]) - the path(s) to use as an alias for `path` ### Returns - **Schema** - the Schema instance ### Example ```javascript const toySchema = new Schema({ n: String }); // Make 'name' an alias for 'n' toySchema.alias('n', 'name'); const Toy = mongoose.model('Toy', toySchema); const turboMan = new Toy({ n: 'Turbo Man' }); turboMan.name; // 'Turbo Man' turboMan.n; // 'Turbo Man' turboMan.name = 'Turbo Man Action Figure'; turboMan.n; // 'Turbo Man Action Figure' await turboMan.save(); // Saves { _id: ..., n: 'Turbo Man Action Figure' } ``` ``` -------------------------------- ### Create Schema with Options Source: https://mongoosejs.com/docs/api/schema.html Create a new schema using Schema.create() with a definition and options object. This is equivalent to using the new Schema() constructor. ```javascript const schema = Schema.create({ name: String }, { toObject: { virtuals: true } }); // Equivalent: const schema2 = new Schema({ name: String }, { toObject: { virtuals: true } }); ``` -------------------------------- ### Create One or More Documents Source: https://mongoosejs.com/docs/api/model.html Use create() as a shortcut to instantiate and save one or more documents. This method triggers the save() middleware. ```javascript // Insert one new `Character` document await Character.create({ name: 'Jean-Luc Picard' }); // Insert multiple new `Character` documents await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]); // Create a new character within a transaction. Note that you **must** // pass an array as the first parameter to `create()` if you want to // specify options. await Character.create([{ name: 'Jean-Luc Picard' }], { session }); ``` -------------------------------- ### Get Connection Option Value Source: https://mongoosejs.com/docs/api/connection.html Use `get()` to retrieve the value of a specific connection option. This method provides direct access to the connection's configuration options. ```javascript conn.get('test'); // returns the 'test' value ``` -------------------------------- ### Retrieving a Field Value with get() Source: https://mongoosejs.com/docs/api/query.html Use get() to retrieve the value of a specific path from an update operation's $set. This is useful for getters/setters that work with both update operations and save(). ```javascript const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } }); query.get('name'); // 'Jean-Luc Picard' ``` -------------------------------- ### Connection.prototype.readyState Source: https://mongoosejs.com/docs/api/connection.html Indicates the current connection state. Emits events for state changes. ```APIDOC ## Connection.prototype.readyState ### Description Connection ready state. Each state change emits its associated event name. * 0 = disconnected * 1 = connected * 2 = connecting * 3 = disconnecting ### Type * «property» ### Example ```javascript conn.on('connected', callback); conn.on('disconnected', callback); ``` ``` -------------------------------- ### Import Mongoose Source: https://mongoosejs.com/docs/transactions.html Import the Mongoose library to begin using its features. ```javascript import mongoose from 'mongoose'; ``` -------------------------------- ### Migrating from Callbacks to Promises/Async/Await in Mongoose Source: https://mongoosejs.com/docs/migrating_to_7.html Demonstrates how to refactor Mongoose functions that previously accepted callbacks to use promises or async/await syntax. Includes examples for both direct promise usage and async/await with try-catch and a custom promise-based error handling pattern. ```javascript // Before conn.startSession(function(err, session) { // ... }); ``` ```javascript // After const session = await conn.startSession(); // Or: conn.startSession().then(session => { /* ... */ }); ``` ```javascript // With error handling try { await conn.startSession(); } catch (err) { /* ... */ } // Or: const [err, session] = await conn.startSession().then( session => ([null, session]), err => ([err, null]) ); ``` -------------------------------- ### Check Mongoose Version with npm Source: https://mongoosejs.com/docs/check-version.html Use the `npm list mongoose` command to find the installed version of the Mongoose npm package. This command can also help identify multiple installations. ```bash $ npm list mongoose test@ /path/to/test └── mongoose@7.0.3 ``` -------------------------------- ### Connect with Options Source: https://mongoosejs.com/docs/connections.html Use the `connect` method with a URI and an options object to configure the connection. These options are passed to the underlying MongoDB driver. ```javascript mongoose.connect(uri, options); ``` -------------------------------- ### Configure Collection Creation Options Source: https://mongoosejs.com/docs/guide.html Illustrates using `collectionOptions` to set MongoDB `createCollection()` options like `capped` and `max` for a schema. ```javascript const schema = new Schema({ name: String }, { autoCreate: false, collectionOptions: { capped: true, max: 1000 } }); const Test = mongoose.model('Test', schema); // Equivalent to `createCollection({ capped: true, max: 1000 })` await Test.createCollection(); ``` -------------------------------- ### Race Condition Example Without Optimistic Concurrency Source: https://mongoosejs.com/docs/guide.html This example illustrates a potential race condition where a house can be marked as 'APPROVED' even if its photos are removed concurrently, leading to an inconsistent state. ```javascript const house = await House.findOne({ _id }); if (house.photos.length < 2) { throw new Error('House must have at least two photos!'); } const house2 = await House.findOne({ _id }); house2.photos = []; await house2.save(); // Marks the house as 'APPROVED' even though it has 0 photos! house.status = 'APPROVED'; await house.save(); ``` -------------------------------- ### Get or Set Schema Path Source: https://mongoosejs.com/docs/api/schema.html Retrieves or modifies a schema path. Use arity 1 to get a path's type, and arity 2 to set or change a path's type. ```javascript schema.path('name') // returns a SchemaType schema.path('name', Number) // changes the schemaType of `name` to Number ``` -------------------------------- ### Using Getter, Setter, and Alias for Number Schema Source: https://mongoosejs.com/docs/schematypes.html Illustrates how to use `get`, `set`, and `alias` options for a Number schema type. The `get` and `set` options round the number, and `alias` provides a shorthand for accessing the property. ```javascript const numberSchema = new Schema({ integerOnly: { type: Number, get: v => Math.round(v), set: v => Math.round(v), alias: 'i' } }); const Number = mongoose.model('Number', numberSchema); const doc = new Number(); doc.integerOnly = 2.001; doc.integerOnly; // 2 doc.i; // 2 doc.i = 3.001; doc.integerOnly; // 3 doc.i; // 3 ``` -------------------------------- ### Enable and Override Command Buffering Source: https://mongoosejs.com/docs/guide.html Demonstrates enabling global command buffering and then overriding it with `bufferCommands: false` at the schema level. ```javascript mongoose.set('bufferCommands', true); // Schema option below overrides the above, if the schema option is set. const schema = new Schema({ /* ... */ }, { bufferCommands: false }); ``` -------------------------------- ### Change Stream Data Structure Example Source: https://mongoosejs.com/docs/change-streams.html This is an example of the data structure emitted by a Mongoose change stream when a document is inserted. It includes details like operation type, cluster time, the full document, namespace, and document key. ```json { _id: { _data: '8262408DAC000000012B022C0100296E5A10042890851837DB4792BE6B235E8B85489F46645F6964006462408DAC6F5C42FF5EE087A20004' }, operationType: 'insert', clusterTime: new Timestamp({ t: 1648397740, i: 1 }), fullDocument: { _id: new ObjectId("62408dac6f5c42ff5ee087a2"), name: 'Axl Rose', __v: 0 }, ns: { db: 'test', coll: 'people' }, documentKey: { _id: new ObjectId("62408dac6f5c42ff5ee087a2") } } ``` -------------------------------- ### Initializing Mongoose Connection Without Immediate Connection Source: https://mongoosejs.com/docs/api/mongoose.html Demonstrates how to initialize a Mongoose connection instance without immediately connecting, and then opening the connection later using `openUri()`. ```javascript // initialize now, connect later db = mongoose.createConnection(); await db.openUri('mongodb://127.0.0.1:27017/database'); ``` -------------------------------- ### Query.prototype.getPopulatedPaths() Source: https://mongoosejs.com/docs/api/query.html Gets a list of paths that are populated by this query. ```APIDOC ## Query.prototype.getPopulatedPaths() ### Description Gets a list of paths to be populated by this query. ### Returns * `Array` - An array of strings representing populated paths. ### Request Example ```javascript bookSchema.pre('findOne', function() { let keys = this.getPopulatedPaths(); // ['author'] }); ... Book.findOne({}).populate('author'); ``` ### Request Example ```javascript // Deep populate const q = L1.find().populate({ path: 'level2', populate: { path: 'level3' } }); q.getPopulatedPaths(); // ['level2', 'level2.level3'] ``` ``` -------------------------------- ### Connection.prototype.name Source: https://mongoosejs.com/docs/api/connection.html Gets the name of the database that this connection is currently pointing to. ```APIDOC ## `Connection.prototype.name` ### Description The name of the database this connection points to. ### Type * «property» ### Example ```javascript mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').name; // "mydb" ``` ``` -------------------------------- ### Using mongoose-lean-virtuals Plugin Source: https://mongoosejs.com/docs/tutorials/lean.html Demonstrates how to use the mongoose-lean-virtuals plugin with a schema to enable virtuals on lean documents. Note that `this` will be a POJO in virtuals, getters, and default functions when using lean(). ```javascript const schema = new Schema({ name: String }); schema.plugin(require('mongoose-lean-virtuals')); schema.virtual('lowercase', function() { this instanceof mongoose.Document; // false this.name; // Works this.get('name'); // Crashes because `this` is not a Mongoose document. }); ``` -------------------------------- ### Get SchemaType Path Source: https://mongoosejs.com/docs/api/schematype.html Access the name of a SchemaType within a Schema. ```javascript const schema = new Schema({ name: String }); schema.path('name').path; // 'name' ``` -------------------------------- ### Creating Mongoose Connections with URI Source: https://mongoosejs.com/docs/api/mongoose.html Shows how to create a Mongoose connection using a MongoDB URI, with and without additional options. ```javascript // 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); ``` -------------------------------- ### Get Database Name Source: https://mongoosejs.com/docs/api/connection.html Retrieve the name of the database that this connection is pointing to. ```javascript mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').name; // "mydb" ``` -------------------------------- ### Create and Use a Mongoose Model Source: https://mongoosejs.com/docs/api/model.html Defines a 'User' Model and demonstrates creating new documents, saving them, and querying the database. ```javascript // `UserModel` is a "Model", a subclass of `mongoose.Model`. const UserModel = mongoose.model('User', new Schema({ name: String })); // You can use a Model to create new documents using `new`: const userDoc = new UserModel({ name: 'Foo' }); await userDoc.save(); // You also use a model to create queries: const userFromDb = await UserModel.findOne({ name: 'Foo' }); ``` -------------------------------- ### Get Connection Port Source: https://mongoosejs.com/docs/api/connection.html Access the port number from a MongoDB connection URI. ```javascript mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').port; // 27017 ``` -------------------------------- ### Populating a Virtual Property Source: https://mongoosejs.com/docs/populate.html Demonstrates how to use `populate()` on the virtual 'posts' property of an `Author` document to retrieve associated blog posts. ```javascript const author = await Author.findOne().populate('posts'); author.posts[0].title; // Title of the first blog post ``` -------------------------------- ### Connection.prototype.startSession() Source: https://mongoosejs.com/docs/api/connection.html Starts a MongoDB session, enabling features like causal consistency, retryable writes, and transactions. Requires MongoDB version 3.6.0 or higher. ```APIDOC ## Connection.prototype.startSession() ### Description Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions. _Requires MongoDB >= 3.6.0._ ### Parameters * `[options]` «object» see the mongodb driver options * `[options.causalConsistency=true]` «boolean» set to false to disable causal consistency ### Returns * «Promise» promise that resolves to a MongoDB driver `ClientSession` ### Example ```javascript const session = await conn.startSession(); let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); await doc.deleteOne(); // `doc` will always be null, even if reading from a replica set // secondary. Without causal consistency, it is possible to // get a doc back from the below query if the query reads from a // secondary that is experiencing replication lag. doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); ``` ``` -------------------------------- ### Mongoose.version Source: https://mongoosejs.com/docs/api/mongoose.html The Mongoose version property. This provides the currently installed version of the Mongoose library. ```APIDOC ## Mongoose.version ### Description Provides the currently installed version of the Mongoose library. ### Method N/A (This is a property, not a method.) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript console.log(mongoose.version); // '5.x.x' ``` ### Response #### Success Response (string) - **version** (string) - The Mongoose version string (e.g., '5.x.x'). #### Response Example ```javascript // Example output: // '5.13.15' ``` ``` -------------------------------- ### Basic Timestamps Usage Source: https://mongoosejs.com/docs/timestamps.html Demonstrates how to enable timestamps in a schema and shows the initial values and how they update after a save and a findOneAndUpdate operation. ```javascript const userSchema = new Schema({ name: String }, { timestamps: true }); const User = mongoose.model('User', userSchema); let doc = await User.create({ name: 'test' }); console.log(doc.createdAt); // 2022-02-26T16:37:48.244Z console.log(doc.updatedAt); // 2022-02-26T16:37:48.244Z doc.name = 'test2'; await doc.save(); console.log(doc.createdAt); // 2022-02-26T16:37:48.244Z console.log(doc.updatedAt); // 2022-02-26T16:37:48.307Z doc = await User.findOneAndUpdate({ _id: doc._id }, { name: 'test3' }, { returnDocument: 'after' }); console.log(doc.createdAt); // 2022-02-26T16:37:48.244Z console.log(doc.updatedAt); // 2022-02-26T16:37:48.366Z ``` -------------------------------- ### ObjectId Usage Example Source: https://mongoosejs.com/docs/schematypes.html ObjectIds are instances of `mongoose.Types.ObjectId`. They can be converted to strings using `toString()`. ```javascript const Car = mongoose.model('Car', carSchema); const car = new Car(); car.driver = new mongoose.Types.ObjectId(); typeof car.driver; // 'object' car.driver instanceof mongoose.Types.ObjectId; // true car.driver.toString(); // Something like "5e1a0651741b255ddda996c4" ``` -------------------------------- ### Populate Virtuals with Function Match Option Source: https://mongoosejs.com/docs/populate.html Configure the `match` option dynamically by providing a function. This function receives the document being populated as an argument, allowing for context-aware filtering. ```javascript AuthorSchema.virtual('posts', { ref: 'BlogPost', localField: '_id', foreignField: 'author', // Add an additional filter `{ tags: author.favoriteTags }` to the populate query // Mongoose calls the `match` function with the document being populated as the // first argument. match: author => ({ tags: author.favoriteTags }) }); ``` -------------------------------- ### Creating Mongoose Connections for Replica Sets Source: https://mongoosejs.com/docs/api/mongoose.html Illustrates creating a Mongoose connection to a MongoDB replica set, including specifying replica set options. ```javascript // 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); ``` -------------------------------- ### MongooseArray.prototype.includes() Source: https://mongoosejs.com/docs/api/array.html Checks if the array includes a specific object, optionally starting from a given index. ```APIDOC ## MongooseArray.prototype.includes() ### Description Checks if the array includes a specific object, optionally starting from a given index. ### Method `includes(obj, fromIndex)` ### Parameters - `obj` (object): The item to check for inclusion in the array. - `fromIndex` (number): The index from which to start the search (optional). ### Returns - `boolean`: `true` if the object is found, `false` otherwise. ### Example ```javascript console.log(doc.array.includes(5)); // true console.log(doc.array.includes(10, 2)); // false (if starting search from index 2) ``` ``` -------------------------------- ### Execute Transaction with `session.withTransaction()` Source: https://mongoosejs.com/docs/transactions.html Use the `session.withTransaction()` helper to manage transaction creation, commit, abort, and retries for transient errors. This example demonstrates creating a customer within a transaction. ```javascript let session = null; return Customer.createCollection(). then(() => Customer.startSession()). // The `withTransaction()` function's first parameter is a function // that returns a promise. then(_session => { session = _session; return session.withTransaction(() => { return Customer.create([{ name: 'Test' }], { session: session }); }); }). then(() => Customer.countDocuments()). then(count => assert.strictEqual(count, 1)). then(() => session.endSession()); ``` -------------------------------- ### Defining and Populating Virtuals in Mongoose Source: https://mongoosejs.com/docs/tutorials/virtuals.html This example shows how to define a populated virtual in Mongoose. It includes setting up schemas, defining a virtual with 'ref', 'localField', and 'foreignField', and then populating it to retrieve related user data. ```javascript const userSchema = mongoose.Schema({ _id: Number, email: String }); const blogPostSchema = mongoose.Schema({ title: String, authorId: Number }); // When you `populate()` the `author` virtual, Mongoose will find the // first document in the User model whose `_id` matches this document's // `authorId` property. blogPostSchema.virtual('author', { ref: 'User', localField: 'authorId', foreignField: '_id', justOne: true }); const User = mongoose.model('User', userSchema); const BlogPost = mongoose.model('BlogPost', blogPostSchema); await BlogPost.create({ title: 'Introduction to Mongoose', authorId: 1 }); await User.create({ _id: 1, email: 'test@gmail.com' }); const doc = await BlogPost.findOne().populate('author'); doc.author.email; // 'test@gmail.com' ``` -------------------------------- ### Query.prototype.projection() Source: https://mongoosejs.com/docs/api/query.html Gets or sets the current projection (fields) for a query. Passing `null` removes the projection. ```APIDOC ## Query.prototype.projection() ### Description Gets or sets the current projection (fields) for a query. Passing `null` removes the projection. This method overwrites the existing projection, unlike `select()` which modifies it in place. ### Method Not applicable (prototype method) ### Parameters #### Path Parameters - `arg` (object|null) - The projection object to set, or `null` to remove the projection. ### Returns - `object` - The current projection. ### Example ```javascript const q = Model.find(); q.projection(); // null q.select('a b'); q.projection(); // { a: 1, b: 1 } q.projection({ c: 1 }); q.projection(); // { c: 1 } q.projection(null); q.projection(); // null ``` ```