Mongoose Tutorial Last Updated : 05 Aug, 2025 Comments Improve Suggest changes 4 Likes 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 Create Quiz Comment S souravsharma098 Follow 4 Improve S souravsharma098 Follow 4 Improve Article Tags : Web Technologies Node.js MongoDB Mongoose Tutorials Web-Tech Tutorials +2 More Explore Introduction & Installation NodeJS Introduction3 min readNode.js Roadmap: A Complete Guide6 min readHow to Install Node.js on Linux6 min readHow to Install Node.js on Windows5 min readHow to Install NodeJS on MacOS6 min readNode.js vs Browser - Top Differences That Every Developer Should Know6 min readNodeJS REPL (READ, EVAL, PRINT, LOOP)4 min readExplain V8 engine in Node.js7 min readNode.js Web Application Architecture3 min readNodeJS Event Loop5 min readNode.js Modules , Buffer & StreamsNodeJS Modules5 min readWhat are Buffers in Node.js ?4 min readNode.js Streams4 min readNode.js Asynchronous ProgrammingAsync Await in Node.js3 min readPromises in NodeJS7 min readHow to Handle Errors in Node.js ?4 min readException Handling in Node.js3 min readNode.js NPMNodeJS NPM6 min readSteps to Create and Publish NPM packages7 min readIntroduction to NPM scripts2 min readNode.js package.json4 min readWhat is package-lock.json ?3 min readNode.js Deployments & CommunicationNode Debugging2 min readHow to Perform Testing in Node.js ?2 min readUnit Testing of Node.js Application5 min readNODE_ENV Variables and How to Use Them ?2 min readDifference Between Development and Production in Node.js3 min readBest Security Practices in Node.js4 min readDeploying Node.js Applications5 min readHow to Build a Microservices Architecture with NodeJS3 min readNode.js with WebAssembly3 min readResources & ToolsNode.js Web Server6 min readNode Exercises, Practice Questions and Solutions4 min readNode.js Projects9 min readNodeJS Interview Questions and Answers15+ min read Like