Building a Simple Web Server with Node.js and Express
- Backend
- 04 Jun, 2022
The goal of this guide is to quickly build a web server using Node.js, Express, and MongoDB.
General Steps:
- Set Up Express Server in index.js
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
-
Create Database and Collections in MongoDB using MongoDB Compass
-
Set Up Database Configuration in dbConfig.js in the models folder
@localhost:27017
is the url and port of the MongoDB server. Here, the server is running locally, using the default port 27017/node-api
is the name of the database to connect to?authSource=admin
specifies the authentication database to use when authenticating
const mongoose = require('mongoose')
mongoose.connect(
'mongodb://userName:password@localhost:27017/node-api?authSource=admin',
{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
if (!err) console.log('Mongodb connected')
else console.log('Connection error :' + err)
},
)
- Define Models in postsModel.js in the models directory
const mongoose = require('mongoose')
const PostsModel = mongoose.model(
'posts',
{
author: { type: String, required: true },
message: { type: String, required: true },
date: { type: Date, default: Date.now },
},
'posts',
)
module.exports = { PostsModel }
- Create a new file named postsController.js in the routes folder. Import the
postsModel
that we just created. In this controller, we handle CRUD operations for this model and create corresponding routes.
const express = require('express')
const router = express.Router()
// Import the ObjectId data type
// which is used in MongoDB to uniquely identify documents within a collection
const ObjectID = require('mongoose').Types.ObjectId
const { PostsModel } = require('../models/postsModel')
// Read
router.get('/posts', (req, res) => {
PostsModel.find((err, docs) => {
if (!err) res.send(docs)
else console.log('Error to get data : ' + err)
})
})
// Create
router.post('/', (req, res) => {
const newRecord = new PostsModel({
author: req.body.author,
message: req.body.message,
})
newRecord.save((err, docs) => {
if (!err) res.send(docs)
else console.log('Error creating new data : ' + err)
})
})
// Update
router.put('/:id', (req, res) => {
if (!ObjectID.isValid(req.params.id)) {
return res.status(400).send('ID unknow : ' + req.params.id)
}
const updateRecord = {
author: req.body.author,
message: req.body.message,
}
PostsModel.findByIdAndUpdate(
req.params.id,
{ $set: updateRecord },
{ new: true },
(err, docs) => {
if (!err) res.send(docs)
else console.log('Update error : ' + err)
},
)
})
// Delete
router.delete('/:id', (req, res) => {
if (!ObjectID.isValid(req.params.id)) {
return res.status(400).send('ID unknow : ' + req.params.id)
}
PostsModel.findByIdAndRemove(req.params.id, (err, docs) => {
if (!err) res.send(docs)
else console.log('Delete error : ' + err)
})
})
module.exports = router
- Register Routes in index.js
const postsRoutes = require('./routes/postsController')
app.use('/', postsRoutes)
VoilĂ ! The above is a simple guide on the steps to create a web server using Node.js, Express, and MongoDB.
Happy Coding!