Mongoose Tutorial Last Updated : 05 Aug, 2025 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 S souravsharma098 Follow Improve S souravsharma098 Follow Improve Article Tags : Web Technologies Node.js MongoDB Mongoose Tutorials Web-Tech Tutorials +2 More Explore Node.js Tutorial 3 min read Introduction & Installation NodeJS Introduction 3 min read Node.js Roadmap: A Complete Guide 6 min read How to Install Node.js on Linux 6 min read How to Install Node.js on Windows 5 min read How to Install NodeJS on MacOS 6 min read Node.js vs Browser - Top Differences That Every Developer Should Know 6 min read NodeJS REPL (READ, EVAL, PRINT, LOOP) 4 min read Explain V8 engine in Node.js 7 min read Node.js Web Application Architecture 3 min read NodeJS Event Loop 5 min read Node.js Modules , Buffer & StreamsNodeJS Modules 5 min read What are Buffers in Node.js ? 4 min read Node.js Streams 4 min read Node.js Asynchronous ProgrammingAsync Await in Node.js 3 min read Promises in NodeJS 7 min read How to Handle Errors in Node.js ? 4 min read Exception Handling in Node.js 3 min read Node.js NPMNodeJS NPM 6 min read Steps to Create and Publish NPM packages 7 min read Introduction to NPM scripts 2 min read Node.js package.json 4 min read What is package-lock.json ? 3 min read Node.js Deployments & CommunicationNode Debugging 2 min read How to Perform Testing in Node.js ? 2 min read Unit Testing of Node.js Application 5 min read NODE_ENV Variables and How to Use Them ? 2 min read Difference Between Development and Production in Node.js 3 min read Best Security Practices in Node.js 4 min read Deploying Node.js Applications 5 min read How to Build a Microservices Architecture with NodeJS 3 min read Node.js with WebAssembly 3 min read Resources & ToolsNode.js Web Server 6 min read Node Exercises, Practice Questions and Solutions 4 min read Node.js Projects 9 min read NodeJS Interview Questions and Answers 15+ min read Like