Overview
In Node.js web development, databases like MySQL, PostgreSQL, and MongoDB are vital for storing and retrieving data. They enable operations like create, read, update, and delete (CRUD) and are essential for building dynamic and scalable applications.
Web applications, such as eCommerce sites and social media apps, rely on databases for efficient data storage and retrieval. Beyond storage, databases offer features like data indexing and security. Understanding how to work with databases is crucial for Node.js developers to build robust and efficient applications.
Video Tutorial :
1. Start a fresh Node.js project.
To start a new Node.js project, you can use the npm package manager. Simply open a command prompt or terminal window and go to the folder where you want the project. Then, enter the command “npm init” to initialize the new Node.js project.
npm init
When you run this command, it will ask for details about your project like its name, version, and author. You have the option to either input the information yourself or just press enter to go with the default values.
2. Install the required packages
To add the necessary components for our application, we’ll use npm. In the same command prompt or terminal window, just type the following command:
npm install express mongoose
Running this command will add Express.js and Mongoose packages to your project.
3. Initialize the MongoDB database connection
To make Mongoose work with MongoDB, we have to establish a connection to our MongoDB database. Simply create a new file named server.js in the main directory of your project, and insert the following code:
const mongoose = require("mongoose"); mongoose.connect( "mongodb_url/nodejs_blogpost" ) .then(() => { console.log("MongoDB connected"); app.listen(5000, () => { console.log(`Server started on port 5000`); }); }) .catch((error) => { console.log(error); });
4. Establish a Mongoose schema for our data
With our database connection in place, we can now define the structure of our data by creating a Mongoose schema. In this instance, we’ll craft a straightforward schema for a blog model.
To get started, make a folder named model in the main directory of our project and then inside the model folder create a new file named blogModel.js and insert the following code:
const mongoose = require("mongoose") const blogModel = mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, description: { type: String, required: true }, image: { type: String, required: true }, author: { type: String, required: false, default: "John Doe" }, authorAge: { type: Number, required: false } }, { timestamps: true }) const Blog = mongoose.model("Blog", blogModel); module.exports = Blog;
5. Set up routes to handle CRUD operations.
With our database connection and schema configured, let’s now build routes to manage CRUD (create, read, update, delete) operations on our data.
Now in the server.js file of our project and include the following code:
const express = require("express"); const mongoose = require("mongoose"); const Blog = require("./model/blogModel"); const app = express(); app.use(express.json()); app.get("/", (req, res) => { res.send("This is our home page"); }); app.get("/blog", (req, res) => { res.send("This is our Blog page"); }); app.post("/blogpost", async (req, res) => { try { const blogpost = await Blog.create(req.body); res.status(200).json(blogpost); } catch (error) { console.log(error.message); res.status(500).json({ message: error.message }); } }); app.get("/blogposts", async (req, res) => { try { const blogposts = await Blog.find({}); res.status(200).json(blogposts); } catch (error) { console.log(error.message); res.status(500).json({ message: error.message }); } }); app.get("/blogposts/:id", async (req, res) => { try { // const id = req.params.id; const { id } = req.params; const blogpost = await Blog.findById(id); res.status(200).json(blogpost); } catch (error) { console.log(error.message); res.status(500).json({ message: error.message }); } }); app.put("/blogposts/:id", async (req, res) => { try { // const id = req.params.id; const { id } = req.params; const blogpost = await Blog.findByIdAndUpdate(id, req.body); if (!blogpost) { return res .status(404) .json({ message: `Blogpost not found with ID ${id}` }); } res.status(200).json("blogpost updated"); } catch (error) { console.log(error.message); res.status(500).json({ message: error.message }); } }); app.delete("/blogposts/:id", async (req, res) => { try { // const id = req.params.id; const { id } = req.params; const blogpost = await Blog.findByIdAndDelete(id); if (!blogpost) { return res .status(404) .json({ message: `Blogpost not found with ID ${id}` }); } res.status(200).json("blogpost deleted successfully"); } catch (error) { console.log(error.message); res.status(500).json({ message: error.message }); } });
After downloading, Please follow the steps below:
- open up terminal in the VS code editor
- npm install
- npm run dev
- change MongoDB url
- Test it out