DEV Community

Emdadul Islam
Emdadul Islam

Posted on

Mongoose Cheat Sheet

mongoose

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 }
});

Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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 });

Enter fullscreen mode Exit fullscreen mode

Deleting documents

// Delete a single document by ID
await User.findByIdAndDelete(userId);

// Delete multiple documents that match a query
await User.deleteMany({ isAdmin: false });
Enter fullscreen mode Exit fullscreen mode

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 }
});
Enter fullscreen mode Exit fullscreen mode

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'
  }]
});
Enter fullscreen mode Exit fullscreen mode
const postSchema = new mongoose.Schema({
  title: String,
  content: String,
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
});
Enter fullscreen mode Exit fullscreen mode

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 Postdocuments. The Post model has a field called author, which is an ObjectIdvalue 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');
Enter fullscreen mode Exit fullscreen mode

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)