How to Use MongoDB with Node.js: A Step-by-Step Guide

MongoDB is a popular NoSQL database that pairs well with Node.js for building scalable applications. This guide walks you through connecting Node.js to MongoDB using Mongoose, an ODM library, and performing basic CRUD operations.

Start by installing Mongoose in your Node.js project: npm install mongoose. Then, create a connection to your MongoDB instance (local or cloud via Atlas). Use mongoose.connect('mongodb://localhost:27017/myapp'). Handle connection events for success or error.

Article illustration

1. Define a Schema and Model

In Mongoose, a schema defines the structure of your documents. For example, a User schema with name and email fields. Then compile it into a model: const User = mongoose.model('User', userSchema);.

2. Create and Read Documents

Use new User({...}) and .save() to create. To find documents, use User.find({}) or User.findById(id). Both return promises, so use async/await.

3. Update and Delete Operations

Update with User.findByIdAndUpdate(id, updateData, {new: true}). Delete with User.findByIdAndDelete(id). Always handle errors with try/catch blocks.

4. Query with Conditions

MongoDB supports rich queries. For example, find users older than 18: User.find({ age: { $gt: 18 } }). Use .select(), .sort(), and .limit() for advanced queries.

With these basics, you can integrate MongoDB into your Node.js applications. Explore Mongoose documentation for more advanced features like virtuals, middleware, and population.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *