How to Build a Basic API using Node.js & MongoDB

To build an API with Node.js that interacts with a MongoDB database, you can use a framework like Express.js and a MongoDB driver or ODM (Object Data Modeling) library like Mongoose.

This process involves setting up a Node.js project, connecting to MongoDB, defining API endpoints, and handling HTTP requests. Here’s a step-by-step guide to help you create a basic RESTful API with Node.js and MongoDB.

Step 1: Set Up Node.js Project

  • Initialize a Node.js Project: Create a new directory for your project and initialize a Node.js application with npm init. Follow the prompts to set up your project.

Bash Code

mkdir my-node-api
cd my-node-api
npm init -y
  • Install Dependencies: Install Express.js for the API framework and Mongoose for MongoDB interaction.

Bash Code

npm install express mongoose

Step 2: Connect to MongoDB

  1. Create a MongoDB Connection: In your project directory, create a file named db.js to

JavaScript Code

const mongoose = require('mongoose');

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

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

module.exports = mongoose;

Replace 'mongodb://localhost:27017/mydatabase' with your MongoDB connection string.

Step 3: Define a Model

  1. Create a Model: Define a Mongoose schema for your data and create a model. In this example, we’ll create a simple “User” model.

JavaScript Code

const express = require('express');
const app = express();
const User = require('./user'); // Import the User model
const db = require('./db'); // Import the MongoDB connection

app.use(express.json()); // Middleware to parse JSON request bodies

// Define a simple endpoint to fetch all users
app.get('/users', async (req, res) => {
  try {
    const users = await User.find(); // Fetch all users from MongoDB
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Define an endpoint to add a new user
app.post('/users', async (req, res) => {
  try {
    const newUser = new User(req.body); // Create a new user with the request data
    const savedUser = await newUser.save(); // Save the user to MongoDB
    res.status(201).json(savedUser); // Return the saved user
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Start the Express server
const port = 3000;
app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

This code snippet defines two basic endpoints:

  • GET /users: Retrieves all users from MongoDB.
  • POST /users: Adds a new user to MongoDB.

Step 5: Test the API

  1. Start the Server: Start your Node.js application to test the API.

Bash

node app.js
  1. Send HTTP Requests: Use a tool like Postman or Curl to send HTTP requests to your API endpoints. Verify that the responses are as expected and that the MongoDB operations are successful.

With this setup, you have a basic Node.js API that interacts with a MongoDB database using Express.js and Mongoose. You can expand this structure to add more endpoints, business logic, error handling, and additional features as needed for your application.