Mongoose Tutorial Last Updated : 14 Dec, 2024 Comments Improve Suggest changes Like Article Like Report Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seamless integration with Node.js applications.Provides schema-based modeling to define document structure.Includes built-in validation to ensure data consistency.Enables easy querying and data relationships with chain query methods.To Start with Mongoose, you need to install and import it into your project. Follow these articles to install depending on your system:How to Use MongoDB and Mongoose with Node.jsnpm mongooseLet us now take a look at our first code example. JavaScript //import mongoose in the application const mongoose = require('mongoose'); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/myDatabase', { useNewUrlParser: true, useUnifiedTopology: true, }); // Define a schema const userSchema = new mongoose.Schema({ name: String, age: Number, email: String, }); // Create a model const User = mongoose.model('User', userSchema); // Insert a document const user = new User({ name: 'Mohit Kumar', age: 25, email: '[email protected]', }); user.save() .then(() => console.log('User saved')) .catch((err) => console.error('Error:', err)); It will insert a document with the provided details into the User collection in MongoDB.In this exampleMongoose connects to a local MongoDB database using mongoose.connect().A schema is defined (userSchema) to enforce the structure of documents in the User collection.A model (User) is created based on the schema, acting as an interface for database operations.A new User instance is created and saved to the database using the .save() method.Mongoose Tutorial -GeeksforGeeksWhy Learn Mongoose?Simplifies MongoDB operations with built-in schema validation.Reduces boilerplate code for database interactions.Supports middleware for pre/post operations.Well-suited for Node.js applications.Mongoose Tutorial Prerequisites: JavaScript, Node.js, and MongoDB basicsMongoose BasicsConnect Node to database using MongooseMongoose Module IntroductionMongoose ConnectionsMongoose SchematypeMongoose SchemaType OptionsMongoose Schema APIMongoose Schemas VirtualsMongoose Schemas IndexesMongoose Document APIMongoose DocumentsMongoose PluginsMongoose PopulateMongoose QueriesMongoose VirtualsCRUD Operations Using MongooseMongoose Documents vs ModelsMongoose Schemas Creating a modelMongoose ValidationAggregation in MongoDBTransactions in MongooseMongoose FunctionsMongoose Populate() methodMongoose find() FunctionMongoose where() FunctionMongoose remove() FunctionMongoose exists() FunctionMongoose update() FunctionMongoose insertMany() FunctionMongoose findById() FunctionMongoose findByIdAndDelete() FunctionMongoose findByIdAndUpdate() FunctionMongoose findByIdAndRemove() FunctionMongoose findOneAndDelete() FunctionMongoose findOneAndUpdate() FunctionMongoose findOneAndReplace() FunctionMongoose findOneAndRemove() FunctionMongoose replaceOne() FunctionMongoose updateOne() FunctionMongoose updateMany() FunctionMongoose insertMany() FunctionMongoose findOne() FunctionMongoose deleteOne() FunctionMongoose ProjectsLogin form using Node JS and MongoDBUpload and Retrieve Image on MongoDB using MongoosePagination on an APINodejs – Connect MongoDB with Node app using MongooseJSSignup Form Using Nodejs and MongoDBLogin form using Node.js and MongoDBConnect Django Project to MongoDB using DjangoMongoDB IntroductionHow do Document Databases Work?How MongoDB works?MongoDB: An introductionWhat is MongoDB – Working and FeaturesDifference between RDBMS and MongoDBMongoDB vs MySQLMongoDB InstallationHow to Install and Configure MongoDB in Ubuntu?How to install MongoDB on MacOS?How to install MongoDB on Windows?Basics of MongoDBMongoDB – Database, Collection, and DocumentMongoDB CursorDataTypes in MongoDBWhat is ObjectId in MongoDBWhat is a MongoDB Query?MongoDB | Create a Database using MongoShellMongoDB | Delete Database using MongoShellMongoDB CRUD operationsMongoDB MethodsMongoDB – Insert() MethodMongoDB – insertOne() MethodMongoDB – insertMany() MethodMongoDB – Bulk.insert() MethodMongoDB – bulkWrite() MethodMongoDB – Update() MethodMongoDB – updateOne() MethodMongoDB – updateMany() MethodMongoDB – Find() MethodMongoDB – FindAndModify() MethodMongoDB – sort() MethodMongoDB – copyTo() MethodMongoDB – count() MethodMongoDB – countDocuments() MethodMongoDB – drop() MethodMongoDB – Remove() MethodMongoDB – deleteOne() MethodMongoDB – getIndexes() MethodMongoDB – dropIndex() MethodMongoDB – dropIndexes() MethodMongoDB OperatorsComparison OperatorsMongoDB – Comparison Query OperatorsMongoDB $cmp OperatorMongoDB – Greater than Operator $gtMongoDB – Less than Operator $ltMongoDB – Equality Operator $eqMongoDB – Less than equals to Operator $lteMongoDB – Greater than equals to Operator $gteMongoDB – Inequality Operator $neMongoDB $in OperatorMongoDB – $nin OperatorLogical OperatorsMongoDB – Logical Query OperatorsMongoDB AND operator ( $and )MongoDB OR operator ( $or )MongoDB NOT operator ( $not )MongoDB NOR operator ( $nor )Arithmetic OperatorsMongoDB $add OperatorMongoDB $subtract OperatorMongoDB $multiply OperatorMongoDB $divide OperatorMongoDB $abs OperatorMongoDB $floor OperatorMongoDB $ceil OperatorMongoDB $mod OperatorMongoDB $sqrt OperatorMongoDB $pow OperatorMongoDB $exp OperatorMongoDB $log OperatorMongoDB $log10 OperatorMongoDB $ln OperatorField Update OperatorsMongoDB – Field Update OperatorsMongoDB – Maximum operator ( $max )MongoDB – Minimum operator ( $min )MongoDB – Increment Operator ( $inc )MongoDB – Multiply Operator ($mul)MongoDB – Rename Operator ($rename)MongoDB – Current Date Operator ($currentDate)MongoDB – SetOnInsert Operator ($setOnInsert)MongoDB Bitwise Update OperatorArray Expression OperatorsMongoDB $isArray OperatorMongoDB $size OperatorMongoDB $arrayElemAt OperatorMongoDB $concatArrays OperatorMongoDB $reverseArray OperatorArray Update OperatorsMongoDB – $pull OperatorMongoDB – $pop OperatorMongoDB – $pullAll OperatorMongoDB – $push OperatorMongoDB – Positional Operator ($)MongoDB – All Positional Operator ($[])MongoDB – $position ModifierMongoDB – $addToSet OperatorMongoDB – $each ModifierMongoDB – $sort ModifierMongoDB – $slice ModifierString Expression OperatorsMongoDB $concat OperatorMongoDB $strcasecmp OperatorMongoDB $toUpper OperatorMongoDB $toLower Operator$substrCP (aggregation) operator in MongoDBWorking with Documents and CollectionsDefining, Creating, and Dropping a MongoDB collectionAdding and Querying the data in MongoDBHow to Create Database & Collection in MongoDBMongoDB – Query Documents using Mongo ShellMongoDB – Insert Single Document Using MongoShellMongoDB – Insert Multiple Document Using MongoShellMongoDB – Update Single Document Using MongoShellMongoDB – Update Multiple Documents Using MongoShellMongoDB – Replace Documents Using MongoShellMongoDB – Delete Single Document Using MongoShellMongoDB – Delete Multiple Documents Using MongoShellMongoDB – Check the existence of the fields in the specified collectionSorting Documents in MongoDBCapped Collections in MongoDBIndexing in MongoDBIndexing in MongoDBMongoDB Index TypesMongoDB – Compound IndexesMongoDB – Text IndexesMongoDB – Multikey IndexesMongoDB AdvanceExport data from MongoDBImport data to MongoDBMongoDB – RegexMongoDB ProjectionMongoDB – Embedded DocumentsMongoDB – Query Embedded Documents Using Mongo ShellAggregation in MongoDBHow to Enable Authentication on MongoDB?Create a user and add a role in MongoDBMongoDB – Replication and ShardingMongoDB – Backup and RestorationMongoDB For InterviewTop 50 MongoDB Interview Questions with Answers for 2024MongoDB Interview Experience for Backend developerMongoDB ExercisesMongoDB Cheat Sheet (Basic to Advanced)30 Days of Mongo DB: A Complete Beginners GuideAdvantages of MongooseSchema Definition: Mongoose allows you to define structured schema model for MongoDB collections, because of that you get a clear understanding about the structure of model data.Data Validation: It can be used for data validation, which ensures that only valid and properly formatted data is stored in the database, which helps to manage data integrity.Middleware Support: Mongoose has the support of middleware which helps in the execution of custom logic before or after database operations, that offers flexibility in handling data interactions.Query Building: We don't have to write those complex queries which we were writing in MongoDB because Mongoose simplifies the process by providing a high-level API that makes it easier to interact with the database.Modeling Relationships and Population: You can define relationships between different data models and it also supports population, due to this you can work with related data without disturbing database normalization. Mongoose vs MongoDB Native DriverFeatureMongooseMongoDB Native DriverAbstraction LevelHigh (uses models and schemas)Low (raw queries)Data ValidationBuilt-inManualMiddleware SupportYesNoLearning CurveModerateSteeperUse CaseComplex ApplicationsLightweight Apps or ScriptsMore on Mongoose:For more article, you can read recently published article's on MongoDB: Recent Article on MongoDB and Mongoose: Recent articles on Mongoose Comment More infoAdvertise with us Next Article Mongoose Schemas Creating a Model S souravsharma098 Follow Improve Article Tags : Web Technologies Node.js MongoDB Mongoose Tutorials Web-Tech Tutorials +2 More Similar Reads Mongoose Tutorial Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam 6 min read Mongoose SchemasMongoose Schemas Creating a ModelMongoose is one of the most popular Object Data Modeling (ODM) libraries for MongoDB, providing schema-based solutions to model our application's data. This allows us to define the structure of documents within a MongoDB collection, including validation, typecasting, and other powerful features that 5 min read Mongoose Schemas and IndexesMongoose is a powerful Object Data Modeling (ODM) library for MongoDB in a Node.js environment. It provides a straightforward way to interact with MongoDB, including features like schema definition, model creation, and database query handling. One key feature of Mongoose is its ability to create and 5 min read Mongoose Schemas Instance methodsMongoose is a powerful Object Data Modeling (ODM) library for MongoDB, designed to work in a Node.js environment. One of the key features of Mongoose is its ability to define instance methods on schema objects, which allow you to perform operations on individual documents. This guide will explore Mo 5 min read Mongoose Schemas IdsMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn't allow us to save or create a 2 min read Mongoose Schemas VirtualsVirtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, weâll dive 6 min read Mongoose Schemas AliasesMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Aliases help in converting a short property name in the database into a longer, more verbal, property name to enhance code readability. Creating node application And Installing Mongoose: Step 1: Create a 2 min read Mongoose Schemas With ES6 ClassesMongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself. By using loadClass() method: ES6 class methods will become Mongoose methodsES6 class statics will bec 2 min read Mongoose Schemas Query HelpersMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schema Query Helpers are like instance methods for Mongoose queries. These query helpers can be used to filter out mongoose query results or perform additional operations on the existing result. Creating node appl 3 min read Mongoose SchemaTypesMongoose SchemaTypeMongoose is a powerful Object Data Modeling (ODM) library for MongoDB, providing a straightforward way to define the structure of documents, enforce validation, and handle database interactions. Mongoose SchemaTypes are key components that define the types of data stored in MongoDB collections, such 6 min read Mongoose SchemaType OptionsMongoose is a robust object data modeling (ODM) library for MongoDB and Node.js that makes database interactions easy. One of Mongoose's main features is its SchemaType options, which developers can use to specify the shape and behavior of data in MongoDB. Mastering these options is important to mak 5 min read Mongoose SchemaTypes The type KeyThe Mongoose SchemaType has a special property named type. Each property of a Schema needs to have some type. When mongoose sees the nested property named type with a valid value, it assumes that a SchemaType has to be declared with the given type. Syntax: Schema({ property : { type: value // other 3 min read Mongoose SchemaTypes GettersMongoose is a popular Object Data Modeling (ODM) library for MongoDB in Node.js and MongoDB. Mongoose can define custom getters and setters for schema fields using SchemaTypes. Getters allow you to define a function that transforms the raw value of a schema field before it is returned from the datab 7 min read Mongoose SchemaTypes schema.path() FunctionThe Mongoose SchemaTypes schema.path() function is used to get the instantiated schema type for a given path. This function can be used to inspect the schema type and validator for a given path. Syntax: schema.path( propertyName ); Parameters: It accepts a single parameter as mentioned above and de 3 min read Mongoose DocumentsMongoose DocumentsMongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js, making it easier to interact with MongoDB databases. It provides a structured way to handle data, perform validation, and manage documents in MongoDB with ease. In this article, we will explain Mongoose Documents, how 5 min read Mongoose Documents vs ModelsMongoose is a widely used Node library commonly used for working with MongoDB, a NoSQL database. Mongoose streamlines the process of working with MongoDB through an object data modeling (ODM) framework. Two of the primary concepts in the Mongoose environment are Documents and Models. In this article 6 min read Mongoose Documents Updating Using save()An important aspect of a mongoose model is to save the document explicitly when changes have been made to it. This is done using the save() method. In this article, we will see its uses and see the things we should keep in mind while saving our document.We will take the help of an example to underst 5 min read Mongoose QueriesMongoose QueriesMongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an 7 min read Mongoose deleteMany() FunctionThe deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option. This method is essential for Node.js developers working with Mongoose, as it 4 min read Mongoose Queries Model.replaceOne() FunctionThe Queries Model.replaceOne() function of the Mongoose API is used to replace an existing document with the given document. It replaces only the first document that is returned in the filter. Syntax: Model.replaceOne( filter, doc, options, callback ) Parameters: It accepts the following 4 parameter 3 min read Find() Method in MongooseThe Mongoose find() method is one of the most widely used methods for querying MongoDB collections in Node.js. It provides a flexible and powerful way to fetch data from your MongoDB database. In this article, we will explore the find() method in detail, its syntax, parameters, and how to implement 5 min read FindById Method in MongooseThe findById() method in Mongoose is one of the most commonly used methods for retrieving a document by its unique identifier (_id) in a MongoDB collection. This article will cover everything we need to know about how to use the findById() method, including syntax, examples, installation, and troubl 4 min read Mongoose QueriesModel.findByIdAndDelete() MethodThe Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo 4 min read Mongoose findByIdAndRemove() FunctionMongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific i 2 min read Mongoose QueriesModel.findByIdAndDelete() MethodThe Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo 4 min read FindOne() Method in MongooseThe findOne() method in Mongoose is one of the most commonly used functions for querying data from a MongoDB database. It provides a simple and efficient way to retrieve a single document that matches a specified query condition. This article will explore how to use the findOne() method, explain its 5 min read Mongoose findOneAndDelete() FunctionThe findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In 5 min read Mongoose | findOneAndRemove() FunctionThe findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter installin 2 min read Mongoose | findOneAndReplace() FunctionWhen working with MongoDB in Node.js, Mongoose is an essential tool for schema-based modeling and database operations. One of the most powerful and frequently used functions in Mongoose is findOneAndReplace(). This function helps in finding a document and replacing it with a new one. But how exactly 5 min read Mongoose Queries Model.findOneAndUpdate() FunctionThe Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, opt 3 min read Mongoose Document Model.replaceOne() APIThe Model.replaceOne() method of the Mongoose API is used to replace any one document in a collection. This method works the same as the update method but it replaces MongoDB's existing document with the given document with any atomic operator i.e $set. Syntax: Model.replaceOne() Parameters:  The Mo 3 min read updateMany() Method in MongooseIn Mongoose, the updateMany() method is a powerful tool for performing bulk updates in MongoDB. It updates multiple documents that match a specified condition, applying the changes to all the matched documents in a single operation. Unlike updateOne(), which updates only the first matching document, 4 min read Mongoose Queries Model.updateOne() FunctionThe Model.updateOne() function in Mongoose is a powerful method used to update a single document within a MongoDB collection. It allows you to specify the conditions for selecting a document and then provides a way to apply updates to that document. In this article, we will explore how updateOne() w 4 min read Mongoose PopulateMongoose PopulateMongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js. One of the most powerful features it provides is the ability to populate document fields with data from other collections. Mongoose's populate() method enables us to reference documents, replacing ObjectId fields with 7 min read Mongoose Populate() MethodThe populate() method in Mongoose is used to automatically replace a field in a document with the actual data from a related document. It simplifies handling referenced documents and helps replace ObjectIds with the actual data from related collections. This article explores the Mongoose populate() 5 min read Mongoose Populate VirtualsMongoose Populate Virtuals refers to the ability to use the populate() method to populate virtual fields in your Mongoose models. Virtual fields, unlike regular fields, do not get stored in the database. Instead, they are computed on the fly based on other document data. In this article, we will exp 7 min read Mongoose Schema API Mongoose Schema APIMongoose is a powerful ODM (Object Document Mapper) tool for Node.js, specifically designed to work with MongoDB. It offers an easy way to define data models, interact with the database, and enforce data integrity in MongoDB through schemas. In this article, we will explore the Mongoose Schema API, 6 min read Mongoose Schema.prototype.pre() MethodThe Mongoose Schema API pre() method is used to add a pre-hook to the mongoose Schema methods and can be used to perform pre Schema method operations. In this article, we will explain the Mongoose Schema.prototype.pre() method, explaining how to use it effectively for pre-operation hooks in your Mon 4 min read Mongoose Schema.prototype.static() MethodMongoose is an essential Object Data Modeling (ODM) library for MongoDB in Node.js. It provides powerful tools to interact with MongoDB using a well-defined schema structure. One of the most useful features of Mongoose is its ability to define static methods on schemas, which allows us to perform cl 5 min read Mongoose Schema.prototype.virtual() APIThe Mongoose Schema API .prototype.virtual() method of the Mongoose API is used on the Schema object. It allows us to define virtual method and type over each schema with a specific name and method definition. Let us understand virtual() method using an example. Syntax: schemaObject.virtual( <nam 2 min read Mongoose Schema.prototype.virtualpath() MethodThe Mongoose Schema API.prototype.virtualpath() method of the Mongoose API is used on the Schema object. It allows us to get the virtual object we have defined over the schema. This method takes the name of virtual as a parameter and return the VirtualType object with several properties. Let us unde 3 min read Mongoose Schema.prototype.virtuals PropertyThe Mongoose Schema API.prototype.virtuals property of the Mongoose API is used on the Schema object. It allows us to get information about virtual we have defined over schema. It is represented in the form of objects where keys are virtual paths we have defined over schema. Let us understand virtua 2 min read Mongoose Connection APIMongoose Schema Connection.prototype.asPromise() APIThe Mongoose Schema API Connection.prototype.asPromise() method of the Mongoose API is used on the Connection object. It allows us to get the result as a promise if the connection to the MongoDB is successfully connected which means the promise is resolved else the promise is rejected. Let us unders 2 min read Mongoose Schema Connection.prototype.close() APIThe Mongoose Schema API Connection.prototype.close() method of the Mongoose API is used on the Connection objects It allows us to close the mongodb connection from the mongoose side. With the help of this method we can forcefully close the connection. Let us understand close() method using an exampl 3 min read Mongoose Schema Connection.prototype.collections APIThe Mongoose Schema API Connection.prototype.collections property of the Mongoose API is used on the Connection object. It allows us to get the details about the collections that are associated with the connection object. Each connection object poses how many collections that information we will get 2 min read Mongoose Schema Connection.prototype.dropCollection() APIThe Connection.prototype.dropCollection() method of the Mongoose API is used on the Connection object. It allows us to delete particular collections from the MongoDB database. With the help of this method, we can remove any collection from the database along with all the documents and indexes associ 2 min read Mongoose Schema Connection.prototype.dropDatabase() APIThe Connection.prototype.dropDatabase() method of the Mongoose API is used on the Connection object. It allows us to delete particular database from MongoDB. Along with the database it will delete collection, documents, and index related data as well. Let us understand dropDatabase() method using an 2 min read Mongoose Schema Connection.prototype.id APIThe Mongoose Schema API Connection.prototype.id of the Mongoose API is used on the Connection objects. It allows us to check how many connections does connection object poses. It is used to debug the connection object when we have multiple connections pointing to one single connection reference. Let 2 min read Mongoose Schema Connection.prototype.model() FunctionThe Mongoose Schema API Connection.prototype.model() of the Mongoose API is used on the Connection objects. It allows us to define new model in the MongoDB database for particular connection object. It is used to define and retrieve models in and from the database. Let us understand models() method 3 min read Mongoose Schema Connection.prototype.models APIMongoose Schema API Connection.prototype.models of the Mongoose API is used on the Connection objects. It allows us to get list of all the models we have defined using connection.model() on a particular connection object. Let us understand the models property using an example. Syntax: connectionObje 2 min read Mongoose Schema Connection.prototype.set() APIThe Connection.prototype.set() method of the Mongoose API is used on the Connection object. It allows us to set the value for keys in the options object. We can provide the key and its value to the set() method in order to set the options for the connection object. Let us understand the set() method 2 min read Mongoose Schema Connection.prototype.useDb() APIThe Connection.prototype.useDb() method of the Mongoose API is used on the Connection object. It allows us to change the current working database. It is used to switch between databases using the same connection pool. Let us understand useDb() method using an example. Syntax: connection.useDb( <d 2 min read Mongoose Schema API Connection.prototype.deleteModel() FunctionThe Connection.prototype.deleteModel() method of the Mongoose API is used on the Connection object. It allows us to remove the model from the connection. Using this method we can clean the model associated with the connection. Let us understand deleteModel() method using an example. Syntax: connecti 3 min read Mongoose Schema API Connection.prototype.modelNames()The Connection.prototype.modelNames() method of the Mongoose API is used on the Connection object. It allows us to get information about all the models that have been created using a particular connection object. Syntax: connection.modelNames( );Parameters: This method does not accept any parameter 2 min read Understanding Mongoose Connection.readyStateThe Connection.prototype.readyState property in Mongoose allows developers to track and manage the current state of a database connection in a MongoDB application. This property returns a numeric value that corresponds to the connectionâs current state, providing a simple way to monitor whether the 3 min read Mongoose Document API Mongoose Document APIMongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js, designed to work in an asynchronous environment. Mongoose provides a straightforward API to interact with MongoDB. It allows you to model your application data and perform operations like create, read, update, and delete (CRU 6 min read Mongoose Document.prototype.$isDefault() APIThe Document API.prototype.$isDefault() method of the Mongoose API is used on the Document model. It allows us to check whether a particular field in Schema has a default value or not. While defining schema we can set the default value for the fields. Let us understand the isDefault() method using a 3 min read Mongoose Document.prototype.$isDeleted() APIThe Document API.prototype.$isDeleted() method of the Mongoose API is used on the Document model. It allows us to identify whether a document is removed or not. With the help isDeleted() method we can override what mongoose thinks about the document is deleted or not Let us understand isDeleted() me 3 min read Mongoose Document.prototype.$isEmpty() APIThe Document API.prototype.$isEmpty() method of the Mongoose API is used on the Document model. It allows us verify whether any field in the document is empty or not. If any specific field in the document object is not having value, then the isEmpty() method will return true else it will return fals 3 min read Mongoose Document.prototype.$isNew APIThe Document API.prototype.$isNew property of the Mongoose API is used on the Document model. It allows us verify whether a document is newly created. When a document is create using new keyword that document object is considered as a new document. Using this concept mongoose decides while saving th 3 min read Mongoose Document.prototype.$op APIThe Document API.prototype.$op property of the Mongoose API is used on the Document model. It allows us to determine the ongoing operation mongoose in performing or executing on the document object. It may be null, save, validate or remove. Let us understand the $op property using an example. Syntax 3 min read Mongoose Document.prototype.directModifiedPaths() APIThe Document API.prototype.directModifiedPaths() method of the Mongoose API is used on the Document model. It allows us to get the list of fields which we have modified directly or fields which are explicitly modified. Let us understand directModifiedPaths() method using an example.  Syntax: documen 3 min read Mongoose Document.prototype.equals() APIThe Document API.prototype.equals() method of the Mongoose API is used on the Document Model object. It allows us to verify whether two document objects are equal or not. This method will return true if one document is equal to another document. This method uses the _id  field of documents to compar 3 min read Mongoose Document.prototype.isSelected() APIThe Document API.prototype.isSelected() method of the Mongoose API is used on the Document model. It allows us to check whether specific path or field is selected in the query to be included in the result set or not. It returns a Boolean value.  Syntax: document.isSelected( path ) Parameters: This m 3 min read Mongoose Document.prototype.toJSON() APIThe Mongoose Document API.prototype.toJSON() method of the Mongoose API is used on the Document model. It allows to convert the result set into JSON object. The converted JSON object then can be used as a parameter to the JSON.stringify() method. Let us understand the toJSON() method using an exampl 3 min read Mongoose Document.prototype.toString() APIThe Mongoose Document API.prototype.toString() method of the Mongoose API is used on the Document model. It allows to get the result in the form of string. Using this method we can convert the output in String type. Let us understand the toString() method using an example. Syntax: document.toString( 2 min read Mongoose Model APIMongoose Document Model() APIThe Mongoose Document APIModel() method of the Mongoose API is used on the Document model. It allows to create a MongoDB class. Using this method we can create model that can interact with MongoDB for all operations. Let us understand the APIModel() method using an example. Syntax: mongoose.model( d 3 min read Mongoose Document Model.bulkWrite() APIWhen working with MongoDB and Mongoose in Node.js, handling multiple database operations one by one can be slow and inefficient. Thatâs where the Model.bulkWrite() method comes in handy. This powerful API lets you execute multiple write operations (insert, update, delete, replace) in a single comman 4 min read Mongoose Document Model.count() APIThe Model.count() method of the Mongoose API is used to count the number of documents present in the collection based on the given filter condition. It returns the query object and count of documents present in the collection.Syntax:Model.count()Parameters: The Model.count() method accepts two param 2 min read Mongoose Document Model.countDocuments() APIThe Model.countDocuments() method of the Mongoose API is used to count the number of document present in a collection. The countDocument() method count the number of documents in a collection based on matching filter. Model.countDocuments() method accepts four parameters: filter: It is an object to 3 min read Mongoose Model.create() APIIn Node.js applications, Mongoose provides an effective way to interact with MongoDB, allowing developers to define models and schemas to store and retrieve data. One of the essential methods provided by Mongoose is Model.create(), which is used to create one or more documents in a MongoDB collectio 5 min read Mongoose Document Model.deleteMany() APIThe Model.deleteMany() method of the Mongoose API is used to delete more than one document in the collection at a time in one go. We can provide an object which contains a condition to the deleteMany() and can be executed on the model object. It will delete all the documents from the collection that 3 min read Like