How to Use MongoDB and Mongoose to Store and Retrieve Data in Node.js?
6 mins read

How to Use MongoDB and Mongoose to Store and Retrieve Data in Node.js?

Introduction

MongoDB is a popular NoSQL database that allows for the storage and retrieval of data in a flexible and scalable manner. When working with MongoDB in a Node.js application, Mongoose is a powerful tool that provides an Object Data Modeling (ODM) solution, making it easier to work with MongoDB by providing a schema-based solution.

In this article, we will explore how to use MongoDB and Mongoose to store and retrieve data in a Node.js application. We will cover the installation and setup process, creating a connection to the MongoDB database, defining schemas and models using Mongoose, and performing CRUD operations to store and retrieve data.

Prerequisites

Before we dive into the implementation details, make sure you have the following prerequisites installed on your machine:

  1. Node.js: Ensure that you have Node.js installed on your machine. You can download the latest version from the official Node.js website.
  2. MongoDB: Install MongoDB on your machine by following the installation instructions provided in the official MongoDB documentation.
  3. Express: We will be using the Express framework to build our Node.js application. If you are not familiar with Express, it is a fast and minimalist web framework for Node.js. Install Express by running the following command in your project directory:
npm install express

Setting Up the Project

To start building our Node.js application with MongoDB and Mongoose, we need to set up the project structure and install the necessary dependencies.

  1. Create a new directory for your project and navigate into it using the command line:
mkdir my-mongoose-project
cd my-mongoose-project
  1. Initialize a new Node.js project using the following command:
npm init -y

This will create a package.json file with default values.

  1. Install the required dependencies by running the following command:
npm install mongoose

This will install Mongoose, the ODM library we will be using to interact with MongoDB.

Creating a Connection to MongoDB

Now that our project is set up and the dependencies are installed, we can establish a connection to the MongoDB database using Mongoose.

  1. Create a new file called db.js in the root of your project directory.
  2. In the db.js file, import the mongoose module and define a function to establish the connection to the MongoDB database:
const mongoose = require('mongoose');

const connectDB = async () => {
  try {
    await mongoose.connect('mongodb://localhost/mydatabase', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('Connected to MongoDB');
  } catch (error) {
    console.error('Error connecting to MongoDB:', error.message);
    process.exit(1);
  }
};

module.exports = connectDB;
  1. In your main application file (e.g., app.js or index.js), import the connectDB function and call it to establish the connection:
const express = require('express');
const connectDB = require('./db');

const app = express();
const PORT = 3000;

// Connect to MongoDB
connectDB();

// Start the server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

With this setup, we are now connected to the MongoDB database using Mongoose.

Defining Schemas and Models

In MongoDB, data is stored in collections, which are analogous to tables in relational databases. Before we can start storing and retrieving data, we need to define schemas and models using Mongoose.

  1. Create a new file called models.js in the root of your project directory.
  2. In the models.js file, import the mongoose module and define a schema and model for the data you want to store. For example, let’s say we want to store information about books:
const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  publicationYear: {
    type: Number,
    required: true,
  },
});

const Book = mongoose.model('Book', bookSchema);

module.exports = Book;
  1. In your main application file, import the Book model and use it to store and retrieve data. For example, you can create a new book:
const express = require('express');
const connectDB = require('./db');
const Book = require('./models');

const app = express();
const PORT = 3000;

// Connect to MongoDB
connectDB();

// Create a new book
const newBook = new Book({
  title: 'The Great Gatsby',
  author: 'F. Scott Fitzgerald',
  publicationYear: 1925,
});

newBook.save((err) => {
  if (err) {
    console.error('Error saving book:', err);
  } else {
    console.log('Book saved successfully');
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

This code creates a new book object using the Book model and saves it to the database using the save method.

Retrieving Data from MongoDB

To retrieve data from MongoDB, we can use the find method provided by Mongoose. This method allows us to specify conditions and retrieve documents that match those conditions.

  1. In your main application file, add a route to retrieve all books:
// Retrieve all books
app.get('/books', (req, res) => {
  Book.find({}, (err, books) => {
    if (err) {
      console.error('Error retrieving books:', err);
      res.status(500).send('Error retrieving books');
    } else {
      res.json(books);
    }
  });
});

This code defines a GET route /books that retrieves all books from the database and returns them as JSON.

  1. Start the server and test the route by visiting http://localhost:3000/books in your browser or using a tool like Postman.

Conclusion

In this article, we have explored how to use MongoDB and Mongoose to store and retrieve data in a Node.js application. We covered the installation and setup process, creating a connection to the MongoDB database, defining schemas and models using Mongoose, and performing CRUD operations to store and retrieve data.

With MongoDB and Mongoose, you have a powerful combination for working with data in a NoSQL database in a Node.js environment. You can now leverage this knowledge to build robust and scalable applications that take advantage of the flexibility and scalability offered by MongoDB.

Remember to refer to the official documentation for MongoDB and Mongoose for more advanced features and concepts. Happy coding!

Leave a Reply

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