Connects MongoDB with Node.js

MongoDB with Node.js involves several steps. Here’s a high-level overview of the process:

Step 1: Setup Project

  1. Initialize the Project mkdir blog cd blog npm init -y
  2. Install Dependencies npm install express mongoose body-parser

Step 2: Create Project Structure

.
├── models
│ └── Post.js
├── routes
│ └── posts.js
├── .env
├── app.js
└── package.json

Step 3: Setup Environment Variables

Create a .env file in the root of the project with the following content:

MONGO_URI=mongodb://localhost:27017/blog
PORT=3000

Step 4: Create MongoDB Model

Create a Post model in models/Post.js:

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});

module.exports = mongoose.model('Post', PostSchema);

Step 5: Setup Express Application

Create the main application file app.js:

require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

// Middleware
app.use(bodyParser.json());

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

// Routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Step 6: Create Routes

Create the routes for the blog in routes/posts.js:

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

// Get all posts
router.get('/', async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});

// Create a post
router.post('/', async (req, res) => {
const post = new Post({
title: req.body.title,
content: req.body.content
});

try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});

// Get a specific post
router.get('/:postId', async (req, res) => {
try {
const post = await Post.findById(req.params.postId);
res.json(post);
} catch (err) {
res.json({ message: err });
}
});

// Delete a post
router.delete('/:postId', async (req, res) => {
try {
const removedPost = await Post.remove({ _id: req.params.postId });
res.json(removedPost);
} catch (err) {
res.json({ message: err });
}
});

// Update a post
router.patch('/:postId', async (req, res) => {
try {
const updatedPost = await Post.updateOne(
{ _id: req.params.postId },
{ $set: { title: req.body.title, content: req.body.content } }
);
res.json(updatedPost);
} catch (err) {
res.json({ message: err });
}
});

module.exports = router;

Step 7: Run the Application

Start the application:

node app.js

Testing

You can test the API using a tool like Postman or CURL. Below are some example requests:

  1. Get All Posts GET /posts
  2. Create a Post POST /posts Body: { “title”: “Post Title”, “content”: “Post Content” }
  3. Get a Specific Post GET /posts/:postId
  4. Delete a Post DELETE /posts/:postId
  5. Update a Post PATCH /posts/:postId Body: { “title”: “Updated Title”, “content”: “Updated Content” }

This simple blog application demonstrates how to set up a Node.js project, connect it to MongoDB using Mongoose, and perform basic CRUD operations.

RSS
Follow by Email
LinkedIn
Share
Scroll to Top