🐾 Mongoose Cheat Sheet 🚀
Master the essentials of MongoDB object modeling with Mongoose! Level up your backend development skills.
Connecting to MongoDB
Establish a connection to your MongoDB database using Mongoose.
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
🔌 Establish a connection to your MongoDB instance.
Defining a Schema
Create a schema that defines the structure of your MongoDB documents.
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, age: Number, email: String });
📋 Define the fields and data types for your documents.
Creating a Model
Create a model based on the schema to interact with MongoDB.
const User = mongoose.model('User', userSchema);
🔨 Create a model for CRUD operations on 'users' collection.
Inserting Documents
Insert new documents into the collection.
const newUser = new User({ name: 'John', age: 30, email: 'john@example.com' }); newUser.save();
💾 Insert a new document into the 'users' collection.
Querying Documents
Retrieve documents from the collection using queries.
const users = await User.find({ age: { $gt: 25 } });
🔍 Query documents that match certain criteria.
Updating Documents
Update documents using various update methods.
await User.updateOne({ name: 'John' }, { age: 31 });
✏️ Update a document's field(s) in the 'users' collection.
Deleting Documents
Remove documents from the collection.
await User.deleteOne({ name: 'John' });
🗑️ Delete a document from the 'users' collection.
Population (Referencing)
Link documents in different collections using references.
const postSchema = new mongoose.Schema({ title: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } });
🔗 Establish a relationship between 'posts' and 'users'.
Middleware
Use middleware functions for pre and post document actions.
userSchema.pre('save', function(next) { console.log('Saving a user...'); next(); });
🛠️ Execute code before or after certain model actions.