Setting Up a Node.js + MongoDB Project from Scratch

Welcome to today’s tutorial! In this session, we’ll walk through how to set up a Node.js project and integrate it with MongoDB, a NoSQL database. This guide is designed to help you get a basic project up and running, using MongoDB to store data and Node.js to handle the backend.

Prerequisites

Before we get started, make sure you have the following installed on your computer:

  • Node.js and Node Package Manager.
  • MongoDB: Install MongoDB or use a cloud service for a managed database.
  • Code editor: Use any code editor you’re comfortable with (e.g., VS Code, Sublime Text).

Steps for Setting Up a Node.js + MongoDB Project from Scratch

Step 1: Initialize Your Node.js Project

  1. Create a new directory for your project: Open your terminal or command prompt, and navigate to the directory where you want to create your project:

    mkdir node-mongo-project
    cd node-mongo-project
    

     

  2. Initialize a new Node.js project: Run the following command to create a package.json file:
    npm init -y
    

     

Step 2: Install Required Packages

Next, we’ll install the packages we need for our project. You’ll need:

  • Express: A minimal and flexible Node.js web application framework.
  • Mongoose: A MongoDB object modeling tool designed to work in an asynchronous environment.
  • dotenv: A zero-dependency module to load environment variables from a .env file.

Install these dependencies by running:

npm install express mongoose dotenv

Step 3: Set Up MongoDB

Using MongoDB locally: If you have MongoDB installed locally, you can start it by running:

mongod
  • Using MongoDB Atlas: If you don’t have MongoDB installed locally, you can use MongoDB Atlas. Set up a free-tier cluster and get your connection string from the Atlas dashboard.

Step 4: Set Up Project Structure

Now, let’s organize the project by creating the following folder structure:

node-mongo-project/
│
├── models/
│   └── userModel.js
│
├── routes/
│   └── userRoutes.js
│
├── .env
├── app.js
└── package.json

Step 5: Create the .env File

Create a .env file in the root of your project. This file will store sensitive information, like your MongoDB URI, in a safe way. Here’s what it should look like:

MONGO_URI=your_mongodb_connection_string

Make sure to replace your_mongodb_connection_string with your actual MongoDB connection string (from MongoDB Atlas or local MongoDB).

 

Step 6: Create the Server

Let’s create the main file app.js where we will set up Express, connect to MongoDB, and handle routes.

In app.js:

require('dotenv').config(); // Load environment variables from .env file
const express = require('express');
const mongoose = require('mongoose');

// Create an Express app
const app = express();
const port = 3000;

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

// MongoDB connection
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.log('Error connecting to MongoDB:', err));

// Basic route
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

// Import routes (we'll create them next)
const userRoutes = require('./routes/userRoutes');
app.use('/users', userRoutes);

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

Step 7: Create the Model

In the models directory, create a file userModel.js. This will define how user data is structured in the database using Mongoose.

In models/userModel.js:

const mongoose = require('mongoose');

// Define the schema for a user
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  }
});

// Create and export the model
const User = mongoose.model('User', userSchema);
module.exports = User;

Step 8: Create the Routes

Next, let’s create the routes to handle HTTP requests related to users.

In the routes folder, create a file userRoutes.js:

const express = require('express');
const router = express.Router();
const User = require('../models/userModel');

// GET all users
router.get('/', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// POST a new user
router.post('/', async (req, res) => {
  const user = new User({
    name: req.body.name,
    email: req.body.email
  });

  try {
    const newUser = await user.save();
    res.status(201).json(newUser);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

module.exports = router;

Step 9: Test the Application

Now, let’s test our application:

  1. Start your server by running:
  2. node app.js
  3. Open your browser or Postman and navigate to http://localhost:3000. You should see the message “Hello, world!”
  4. To test the user routes:
      • GET request: Use Postman or any HTTP client to send a GET request to http://localhost:3000/users to retrieve all users.
      • POST request: Send a POST request to the same endpoint with a JSON body like:
        {
          "name": "John Doe",
          "email": "[email protected]"
        }
        

         

Leave a Comment

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

Scroll to Top