Let’s Initialize Node.js (express) + MongoDB (mongoose)

Panat Por
3 min readAug 10, 2023

--

I write this story because I want to use it as a template in the future and share how I use Node.js with MongoDB. And for those who visit this stroy by accident.

My Code: https://github.com/panat54083/Medium_Node.js-MongoDB

Initial the backend with node.js + mongoDB

1- init node.js

Create a new directory for your project and navigate into it.

Run the following command in the terminal to initialize package.json

npm init -y

2- install the mongodb module in the terminal

npm i express mongoose

3- set up a server

create server.js file in your root directory

// server.js

const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});

Optional: try to run node server.js . If it can run perfectly, then go to the next step.

4- set up mongodb

create db.js file in your root directory.

// db.js

const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost:27017/your-database-name';

mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(error => console.error('MongoDB connection error:', error));

update server.js file. We need to import db.js .

// server.js

require("./db.js")

// ... other code

Optional 1: try to run node server.js . If there is a MongoDB connection error, try to change localhost to 0.0.0.0 or 127.0.0.1.

Optional 2: I used to get some trouble but I forgot about it but I fixed by downloading MongoDB Community Server .

Initial CRUD Operations

1- Create Model

create file named models for storing the MongoDB model.

  • I suppose I want to create the Customer Model.
// models/Customer.js

const mongoose = require("mongoose");

const customerSchema = new mongoose.Schema(
{
email: {
type: String,
required: "Email is required!",
},
name: {
type: String,
required: "Name is required!",
},
age: {
type: Number,
},
},
{
timestamps: true,
}
);

module.exports = mongoose.model("Customer", customerSchema);

update the db.js file

// db.js

// ...Other code

//Model Setup
require("./models/Customer")

2- Create Controller

create file named Controller for storing the MongoDB controller.

  • I want to create the register function for Customer.
// controllers/Customer.js

const mongoose = require("mongoose");
const Customer = mongoose.model("Customer");

// Controller function to register a new customer
exports.registerCustomer = async (req, res) => {
try {
const { email, name, age } = req.body;

// Check if the customer already exists based on email
const existingCustomer = await Customer.findOne({ email });
if (existingCustomer) {
return res.status(400).json({ message: "Customer already exists with this email." });
}

// Create a new customer instance
const newCustomer = new Customer({
email,
name,
age,
});

// Save the new customer to the database
await newCustomer.save();

res.status(201).json({ message: "Customer registered successfully.", customer: newCustomer });
} catch (error) {
console.error("Error registering customer:", error);
res.status(500).json({ message: "Internal server error" });
}
};

3- Create Router

create file named Routers for storing the MongoDB router.

// routes/Customer.js

const router = require("express").Router();
const customerController = require("../controllers/Customer"); // Import the customer controller

// Define route for registering a new customer
router.post("/register", customerController.registerCustomer);

module.exports = router;

update the server.js file

// server.js

require("./db")

const express = require('express');
const app = express();
const port = 3000;

// ------------------------------ Start -----------------------------

// Middleware to parse JSON and URL-encoded data
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//Setup routes
app.use("/api", require("./routes/Customer"));

// ------------------------------ End -------------------------------

app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});

4- Test the api

I use Thunder Client extension of visul studio code

Post: http://localhost:3000/api/register

Response output

Check in MongoDB via Mongo Compass

In conclution

This is all for today. I hope this story can help you guys somehow. 😉

--

--