If you're working with Mongoose, the popular object data modelling (ODM) library for MongoDB in Node.js, having a quick reference guide or "cheat sheet" can be incredibly helpful. In this blog post, we provide a concise summary of some of the most commonly used Mongoose methods and syntax, organized by category, to help you work more efficiently and effectively with this powerful ODM.
Schema definition
const { Schema } = require('mongoose');
const userSchema = new Schema({
name: String,
email: { type: String, unique: true },
age: Number,
isAdmin: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now }
});
Model definition
const mongoose = require('mongoose');
const userSchema = require('./userSchema');
const User = mongoose.model('User', userSchema);
Creating a document
const user = new User({
name: 'John Doe',
email: 'johndoe@example.com',
age: 30
});
user.save();
Finding documents
// Find all documents
const users = await User.find();
// Find documents that match a query
const admins = await User.find({ isAdmin: true });
// Find a single document by ID
const user = await User.findById(userId);
Updating documents
// Update a single document by ID
await User.findByIdAndUpdate(userId, { name: 'Jane Doe' });
// Update multiple documents that match a query
await User.updateMany({ isAdmin: true }, { isAdmin: false });
Deleting documents
// Delete a single document by ID
await User.findByIdAndDelete(userId);
// Delete multiple documents that match a query
await User.deleteMany({ isAdmin: false });
Validation
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 18 },
isAdmin: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now }
});
In Mongoose, you can define relationships between models using references or subdocuments.
*Using references:
*
To define a relationship between two models using references, you can use the ref property in a field definition. The ref property specifies the name of the target model. Here's an example:
const userSchema = new mongoose.Schema({
name: String,
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}]
});
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
In this example, we have two models: User
and Post
. The User model has a field called posts, which is an array of ObjectId
values that reference Post
documents. The Post model has a field called author, which is an ObjectId
value that references a User document.
To populate the posts field of a User document with the corresponding Post documents, you can use the populate() function:
const user = await User.findById(userId).populate('posts');
This will retrieve the User document with the specified _id value and then retrieve the Post subdocument with the specified postId value.
Top comments (0)