Database Integration with Node.js and Express using MongoDB

In this guide, we’ll focus on connecting your Node.js application to MongoDB, a popular NoSQL database. By the end, you’ll have a fully functional API that interacts with a database, enabling you to store and retrieve data.

learn how to build a basic RESTful API using Node.js and Express Here

Installing MongoDB and Mongoose:

First, make sure you have MongoDB installed on your machine. You can download and install it from the official MongoDB website (https://www.mongodb.com/try/download/community).

Next, install Mongoose, a MongoDB ODM (Object Document Mapper), to simplify database operations in your Node.js application:

npm install mongoose

Connecting Your RESTful API to MongoDB:

Now, modify your existing app.js file to connect to MongoDB using Mongoose. Replace the previous content with the following:

// app.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

// Define a simple schema
const itemSchema = new mongoose.Schema({
  name: String,
});

const Item = mongoose.model('Item', itemSchema);

app.get('/items', async (req, res) => {
  try {
    const items = await Item.find();
    res.json(items);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

app.get('/items/:id', async (req, res) => {
  const itemId = req.params.id;

  try {
    const item = await Item.findById(itemId);

    if (item) {
      res.json(item);
    } else {
      res.status(404).json({ error: 'Item not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

This code establishes a connection to a local MongoDB instance and defines a simple Item model with a name attribute.

Using the MongoDB Atlas Cloud Service:

If you prefer using a cloud-based MongoDB service like MongoDB Atlas, sign up for an account and create a free cluster. Update the connection string in the mongoose.connect method with your Atlas connection string.

mongoose.connect('mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<database>', { useNewUrlParser: true, useUnifiedTopology: true });

Replace <username>, <password>, <cluster>, and <database> with your MongoDB Atlas credentials.

Testing Your API:

Run your Node.js application using:

node app.js

Visit http://localhost:3000/items in your browser, and you should see an empty array since there are no items in the database yet.

Conclusion:

Congratulations! You’ve successfully connected your Node.js and Express application to MongoDB, allowing you to persistently store and retrieve data. As you continue to develop your API, consider adding features like data validation, error handling, and CRUD (Create, Read, Update, Delete) operations to enhance its functionality. Stay tuned for more articles as we explore additional topics in Node.js development. Happy coding!