{"id":20299107,"url":"https://github.com/rj1221/mongoosecheatsheet","last_synced_at":"2026-05-08T10:31:45.442Z","repository":{"id":183588534,"uuid":"670276642","full_name":"Rj1221/MongooseCheatsheet","owner":"Rj1221","description":"Learn Mongoose with this comprehensive cheat sheet! Master MongoDB interactions in Node.js apps. Essential commands, examples, and concepts provided for beginners and experienced developers. Happy coding!","archived":false,"fork":false,"pushed_at":"2023-07-26T01:27:15.000Z","size":16,"stargazers_count":10,"open_issues_count":0,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-20T14:03:06.289Z","etag":null,"topics":["cheatsheet","javscript","js","mongodb","mongoose"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Rj1221.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-07-24T17:22:58.000Z","updated_at":"2025-03-23T11:02:58.000Z","dependencies_parsed_at":"2025-01-14T10:17:45.218Z","dependency_job_id":"2345f6a3-13f1-4d9e-96a6-6be484a40cda","html_url":"https://github.com/Rj1221/MongooseCheatsheet","commit_stats":null,"previous_names":["rj1221/mongoosecheatsheet"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Rj1221/MongooseCheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rj1221%2FMongooseCheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rj1221%2FMongooseCheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rj1221%2FMongooseCheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rj1221%2FMongooseCheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Rj1221","download_url":"https://codeload.github.com/Rj1221/MongooseCheatsheet/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rj1221%2FMongooseCheatsheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32776579,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-08T08:22:46.396Z","status":"ssl_error","status_checked_at":"2026-05-08T08:22:45.650Z","response_time":54,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","javscript","js","mongodb","mongoose"],"created_at":"2024-11-14T16:13:33.167Z","updated_at":"2026-05-08T10:31:45.424Z","avatar_url":"https://github.com/Rj1221.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Mongoose Cheat Sheet\n\n## Introduction to Mongoose\n\nMongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward and schema-based solution to model your application data and interact with MongoDB collections. This cheat sheet covers the essential concepts and commands for using Mongoose effectively.\n\n\u003cimg src=\"https://miro.medium.com/v2/resize:fit:1050/1*acfAKaDI7uv5GyFnJmiPhA.png\" alt=\"Mongoose Image\" width=\"300px\"/\u003e\n\n## Table of Contents\n1. [Installation](#installation)\n2. [Connecting to MongoDB](#connecting-to-mongodb)\n3. [Defining a Mongoose Schema](#defining-a-mongoose-schema)\n4. [Creating a Model](#creating-a-model)\n5. [CRUD Operations](#crud-operations)\n   - Create\n   - Read\n   - Update\n   - Delete\n6. [Querying with Mongoose](#querying-with-mongoose)\n   - Comparison Operators\n   - Logical Operators\n   - Regular Expressions\n   - Sorting\n   - Pagination\n   - Counting Documents\n7. [Middleware](#middleware)\n   - Document Middleware\n   - Query Middleware\n   - Aggregate Middleware\n8. [Validation](#validation)\n9. [Population](#population)\n10. [Indexes](#indexes)\n11. [Embedding Documents](#embedding-documents)\n12. [References](#references)\n13. [Transactions](#transactions)\n14. [Aggregation](#aggregation)\n15. [Virtuals](#virtuals)\n16. [Plugins](#plugins)\n17. [Debugging](#debugging)\n\n## Installation\n\nInstall Mongoose in your Node.js project using npm or yarn:\n\n```bash\nnpm install mongoose\n```\n\n## Connecting to MongoDB\n\n```javascript\nconst mongoose = require('mongoose');\n\nmongoose.connect('mongodb://localhost/my_database', {\n  useNewUrlParser: true,\n  useUnifiedTopology: true,\n})\n  .then(() =\u003e console.log('Connected to MongoDB'))\n  .catch((err) =\u003e console.error('Error connecting to MongoDB:', err));\n```\n**Example**\n```javascript\n// getting-started.js\nconst mongoose = require(\"mongoose\");\n\nasync function main() {\n  await mongoose\n    .connect(\"mongodb://127.0.0.1:27017/sample\")\n    .then(() =\u003e console.log(\"Connected to MongoDB...\"))\n    .catch((err) =\u003e console.error(\"Could not connect to MongoDB...\", err));\n  // use `await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test');` if your database has auth enabled\n}\nmain().catch((err) =\u003e console.log(err));\nconst userSchema = new mongoose.Schema({\n  name: String,\n  email: { type: String, required: true }, // Added 'required' property for email\n  password: String,\n});\n\nconst User = mongoose.model(\"User\", userSchema);\nconst adder = async () =\u003e {\n  const ss = new User({\n    name: \"sai\",\n    email: \"sai1234@gmail.com\",\n    password: \"1234\",\n  });\n\n  await ss.save();\n};\n\nadder();\n\n```\n\n## Defining a Mongoose Schema\n\n```javascript\nconst mongoose = require('mongoose');\n\nconst userSchema = new mongoose.Schema({\n  name: { type: String, required: true },\n  email: { type: String, required: true, unique: true },\n  age: { type: Number },\n  profileImage: { type: Buffer }, // For storing image data in the database\n});\n\nconst User = mongoose.model('User', userSchema);\n```\n\n## Creating a Model\n```javascript\nconst express = require('express');\nconst multer = require('multer');\nconst upload = multer(); // Middleware for handling multipart/form-data (file uploads)\n\nconst app = express();\n\napp.post('/users', upload.single('profileImage'), async (req, res) =\u003e {\n  const { name, email, age } = req.body;\n  const profileImage = req.file ? req.file.buffer : undefined; // Get the image data from the request\n\n  try {\n    const newUser = new User({ name, email, age, profileImage });\n    await newUser.save();\n    res.send(newUser);\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n});\n```\n\n## CRUD Operations\n\n### Create\n\n```javascript\nconst express = require('express');\nconst multer = require('multer');\nconst upload = multer(); // Middleware for handling multipart/form-data (file uploads)\n\nconst app = express();\n\napp.post('/users', upload.single('profileImage'), async (req, res) =\u003e {\n  const { name, email, age } = req.body;\n  const profileImage = req.file ? req.file.buffer : undefined; // Get the image data from the request\n\n  try {\n    const newUser = new User({ name, email, age, profileImage });\n    await newUser.save();\n    res.send(newUser);\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n});\n```\n\n### Read\n\n```javascript\napp.get('/users', async (req, res) =\u003e {\n  try {\n    const allUsers = await User.find();\n    res.send(allUsers);\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n});\n\napp.get('/users/:userId', async (req, res) =\u003e {\n  const { userId } = req.params;\n  try {\n    const user = await User.findById(userId);\n    res.send(user);\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n});\n```\n\n### Update\n\n```javascript\napp.patch('/users/:userId', async (req, res) =\u003e {\n  const { userId } = req.params;\n  const { age } = req.body;\n\n  try {\n    await User.updateOne({ _id: userId }, { age });\n    res.send('User updated successfully.');\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n});\n```\n\n### Delete\n\n```javascript\napp.delete('/users/:userId', async (req, res) =\u003e {\n  const { userId } = req.params;\n\n  try {\n    await User.deleteOne({ _id: userId });\n    res.send('User deleted successfully.');\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n});\n```\n\n## Querying with Mongoose\n\n### Comparison Operators\n\n```javascript\nconst usersWithAgeGreaterThan25 = await User.find({ age: { $gt: 25 } });\nconst usersWithNameEqualToJohn = await User.find({ name: 'John' });\n```\n\n### Logical Operators\n\n```javascript\nconst usersWithAgeGreaterThan25AndNameEqualToJohn = await User.find({ $and: [{ age: { $gt: 25 } }, { name: 'John' }] });\nconst usersWithAgeGreaterThan25OrNameEqualToJohn = await User.find({ $or: [{ age: { $gt: 25 } }, { name: 'John' }] });\n```\n\n### Regular Expressions\n\n```javascript\nconst usersWithEmailMatchingPattern = await User.find({ email: { $regex: /example\\.com$/ } });\n```\n\n### Sorting\n\n```javascript\nconst sortedUsersByNameAscending = await User.find().sort({ name: 1 });\nconst sortedUsersByAgeDescending = await User.find().sort({ age: -1 });\n```\n\n### Pagination\n\n```javascript\nconst pageSize = 10;\nconst pageNumber = 2;\nconst usersPage = await User.find().skip((pageNumber - 1) * pageSize).limit(pageSize);\n```\n\n### Counting Documents\n\n```javascript\nconst totalUsers = await User.countDocuments();\n```\n\n## Middleware\n\nMiddleware in Mongoose can be used for various purposes, such as image processing before saving an image to the database. For simplicity, we will use middleware for logging.\n\n```javascript\nuserSchema.pre('save', function (next) {\n  console.log('About to save a user.');\n  next();\n});\n```\n\n## Validation\n\n```javascript\nconst userSchema = new mongoose.Schema({\n  name: { type: String, required: true },\n  email: { type: String, required: true, unique: true, validate: /^\\S+@\\S+\\.\\S+$/ },\n  age: { type: Number, min: 18, max: 100 },\n});\n```\n\n## Population\n\n```javascript\nconst userSchema = new mongoose.Schema({\n  name: String,\n  posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }],\n});\n\nconst postSchema = new mongoose.Schema({\n  title: String,\n});\n\nconst User = mongoose.model('User', userSchema);\nconst Post = mongoose.model('Post', postSchema);\n\nconst user = await User.findOne().populate('posts');\n```\n\n## Indexes\n\n```javascript\nuserSchema.index({ name: 1 }); // Single field index\nuserSchema.index({ age: 1, email: 1 }); // Compound index\n```\n\n## Embedding Documents\n\n```javascript\nconst userSchema = new mongoose.Schema({\n  name: String,\n  address: {\n    street: String,\n    city: String,\n    country: String,\n  },\n});\n```\n\n## References\n\n```javascript\nconst userSchema = new mongoose.Schema({\n  name: String,\n  posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }],\n});\n\nconst postSchema = new mongoose.Schema({\n  title: String,\n});\n\nconst User = mongoose.model('User', userSchema);\nconst Post = mongoose.model('Post', postSchema);\n```\n\n## Transactions\n\n```javascript\nconst session = await mongoose.startSession();\nsession.startTransaction();\n\ntry {\n  await newUser.save({ session: session });\n  await newPost.save({ session: session });\n\n  await session.commitTransaction();\n} catch (error) {\n  await session.abortTransaction();\n} finally {\n  session.endSession();\n}\n```\n\n## Aggregation\n\n```javascript\nconst usersWithTotalPosts = await User.aggregate([\n  { $lookup: { from: 'posts', localField\n\n: 'posts', foreignField: '_id', as: 'totalPosts' } },\n  { $project: { name: 1, totalPosts: { $size: '$totalPosts' } } },\n]);\n```\n\n## Virtuals\n\n```javascript\nuserSchema.virtual('fullName').get(function () {\n  return this.firstName + ' ' + this.lastName;\n});\n```\n\n## Plugins\n\n```javascript\nconst mongoose = require('mongoose');\nconst timestampPlugin = require('mongoose-timestamp');\n\nuserSchema.plugin(timestampPlugin);\n```\n\n## Debugging\n\nSet\n\n the `DEBUG` environment variable to `mongoose:*` to enable Mongoose debugging logs:\n\n```bash\nDEBUG=mongoose:* node your-app.js\n```\n\n# Conclusion\n\nIn conclusion, this Mongoose cheat sheet serves as a valuable reference guide for efficiently working with MongoDB in Node.js applications. Covering key concepts such as schema definition, model creation, CRUD operations, querying, middleware, validation, population, and more, it equips developers of all levels with the knowledge to build robust and scalable applications with ease. Happy coding with Mongoose and MongoDB!\n\n## License\n\nThis project is licensed under the [MIT License](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frj1221%2Fmongoosecheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frj1221%2Fmongoosecheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frj1221%2Fmongoosecheatsheet/lists"}