Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 1, 2023 07:21 am GMT

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

Model definition

const mongoose = require('mongoose');const userSchema = require('./userSchema');const User = mongoose.model('User', userSchema);Creating a documentconst user = new User({  name: 'John Doe',  email: '[email protected]',  age: 30});user.save();

Finding documents

// Find all documentsconst users = await User.find();// Find documents that match a queryconst admins = await User.find({ isAdmin: true });// Find a single document by IDconst user = await User.findById(userId);

Updating documents

// Update a single document by IDawait User.findByIdAndUpdate(userId, { name: 'Jane Doe' });// Update multiple documents that match a queryawait User.updateMany({ isAdmin: true }, { isAdmin: false });

Deleting documents

// Delete a single document by IDawait User.findByIdAndDelete(userId);// Delete multiple documents that match a queryawait 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 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');

This will retrieve the User document with the specified _id value and then retrieve the Post subdocument with the specified postId value.


Original Link: https://dev.to/mdadul/mongoose-cheat-sheet-8l1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To