How to create NodeJs application with Mongodb using docker image
Creating a Node.js application with functionality and a simple UI, backed by a MongoDB database, involves several components. I’ll guide you through setting up a basic application that includes these features.
/Nodejsproject
|-- app.js
|-- package.json
|-- /models
|-- Book.js
|-- /public
|-- index.html
|-- script.js
|-- style.css
|-- /routes
|-- bookRoutes.js
Step 1: Initialize Node.js Project
In your project directory:
npm init -y
npm install express mongoose body-parser
Step 2: Set Up MongoDB Model
In /models/Book.js
:
const mongoose = require('mongoose');
const bookSchema = new mongoose.Schema({
title: String,
author: String,
year: Number
});
module.exports = mongoose.model('Book', bookSchema);
Step 3: Set Up Express and Routes
In app.js
:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const bookRoutes = require('./routes/bookRoutes');
const app = express();
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/bookstore', {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bookRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Step 4: Create Book Routes
In /routes/bookRoutes.js
:
const express = require('express');
const router = express.Router();
const Book = require('../models/Book');
// Create Book
router.post('/books', async (req, res) => {
const newBook = new Book(req.body);
await newBook.save();
res.send('Book added');
});
// Read Books
router.get('/books', async (req, res) => {
const books = await Book.find();
res.json(books);
});
// Update Book
router.put('/books/:id', async (req, res) => {
const updatedBook = await Book.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updatedBook);
});
// Delete Book
router.delete('/books/:id', async (req, res) => {
await Book.findByIdAndDelete(req.params.id);
res.send('Book deleted');
});
module.exports = router;
Step 5: Create Frontend (Index Page)
In /public/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bookstore</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Bookstore</h1>
<form id="book-form">
<input type="text" id="title" placeholder="Title" required>
<input type="text" id="author" placeholder="Author" required>
<input type="number" id="year" placeholder="Year" required>
<button type="submit">Add Book</button>
</form>
<ul id="book-list"></ul>
<script src="script.js"></script>
</body>
</html>
In /public/script.js
:
Step 6: Implement CRUD Operations in Frontend
You’ll need to write JavaScript in script.js
to handle CRUD operations. This involves making AJAX requests to your backend endpoints to create, read, update, and delete books.
Here’s an example of how you might implement the “create” and “read” operations:
document.getElementById('book-form').addEventListener('submit', async (e) => {
e.preventDefault();
const title = document.getElementById('title').value;
const author = document.getElementById('author').value;
const year = document.getElementById('year').value;
await fetch('/books', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ title, author, year }),
});
document.getElementById('title').value = '';
document.getElementById('author').value = '';
document.getElementById('year').value = '';
loadBooks();
});
async function loadBooks() {
const response = await fetch('/books');
const books = await response.json();
const list = document.getElementById('book-list');
list.innerHTML = '';
books.forEach(book => {
const li = document.createElement('li');
li.textContent = `${book.title} by ${book.author}, ${book.year}`;
list.appendChild(li);
});
}
loadBooks();
Step 7: Run the Application
- Start your MongoDB server.
- Run
node app.js
to start the Node.js server. - Open your browser and navigate to
http://localhost:3000
.
Please find the github source code: https://github.com/jaganrajagopal/Nodejsmongodb.git
You should now have a basic application . Remember, this example is quite basic. In a production app, you would need to add error handling, input validation, security measures, and perhaps a more advanced front-end framework like React or Angular for a more dynamic UI