Nodejs-Docker YT tutorial updated Code

CRUD APPLICATION CODE

index.js file code

const express = require(“express”);
const mongoose = require(‘mongoose’);

const {
MONGO_USER,
MONGO_PASSWORD,
MONGO_IP,
MONGO_PORT,
} = require(“./Config/config”);

const postRouter = requ…


This content originally appeared on DEV Community and was authored by Sanjeev Saravanan

CRUD APPLICATION CODE

index.js file code

const express = require("express");
const mongoose = require('mongoose');

const {
  MONGO_USER,
  MONGO_PASSWORD,
  MONGO_IP,
  MONGO_PORT,
} = require("./Config/config");

const postRouter = require("./routes/postRoutes");

const app = express();

// Add middleware to parse JSON bodies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Construct MongoDB URL with error handling
const mongoURL = `mongodb://${MONGO_USER || 'root'}:${MONGO_PASSWORD || 'example'}@${MONGO_IP || 'localhost'}:${MONGO_PORT || 27017}/?authSource=admin`;

const connectWithRetry = () => {
  mongoose
    .connect(mongoURL)
    .then(() => console.log("Successfully connected to Database"))
    .catch((e) => {
      console.log("Error connecting to DB:", e);
      setTimeout(connectWithRetry, 5000);  // Retry after 5 seconds
    });
};

connectWithRetry();

app.get("/", (req, res) => {
  res.send("<h1>Hello World</h1>");
});

app.use("/api/v1/posts", postRouter);

const port = process.env.PORT || 3000;

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

postController.js file code

const Post = require("../models/postModel");

// Get all posts
exports.getAllPosts = async (req, res, next) => {
  try {
    const posts = await Post.find();

    res.status(200).json({
      status: "success",
      results: posts.length,
      data: {
        posts,
      },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      status: "fail",
      message: "Server Error",
    });
  }
};

// Get a single post by ID
exports.getOnePost = async (req, res, next) => {
  try {
    const post = await Post.findById(req.params.id);

    if (!post) {
      return res.status(404).json({
        status: "fail",
        message: "Post not found",
      });
    }

    res.status(200).json({
      status: "success",
      data: {
        post,
      },
    });
  } catch (error) {
    console.error(error);
    if (error.name === 'CastError') {
      return res.status(400).json({
        status: "fail",
        message: "Invalid post ID format",
      });
    }
    res.status(500).json({
      status: "fail",
      message: "Server Error",
    });
  }
};

// Create a new post
exports.createPost = async (req, res, next) => {
  try {
    // Check if required fields are present
    if (!req.body.title || !req.body.body) {
      return res.status(400).json({
        status: "fail",
        message: "Missing required fields: title and body are required",
      });
    }

    const post = await Post.create(req.body);

    res.status(201).json({
      status: "success",
      data: {
        post,
      },
    });
  } catch (error) {
    console.error(error);
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        status: "fail",
        message: "Validation Error",
        errors: Object.values(error.errors).map(err => ({
          field: err.path,
          message: err.message
        }))
      });
    }
    res.status(500).json({
      status: "fail",
      message: "Server Error",
    });
  }
};

// Update an existing post by ID
exports.updatePost = async (req, res, next) => {
  try {
    const updatedPost = await Post.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );

    if (!updatedPost) {
      return res.status(404).json({
        status: "fail",
        message: "Post not found",
      });
    }

    res.status(200).json({
      status: "success",
      data: {
        post: updatedPost,
      },
    });
  } catch (error) {
    console.error(error);
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        status: "fail",
        message: "Validation Error",
        errors: Object.values(error.errors).map(err => ({
          field: err.path,
          message: err.message
        }))
      });
    }
    if (error.name === 'CastError') {
      return res.status(400).json({
        status: "fail",
        message: "Invalid post ID format",
      });
    }
    res.status(500).json({
      status: "fail",
      message: "Server Error",
    });
  }
};

// Delete a post by ID
exports.deletePost = async (req, res, next) => {
  try {
    const post = await Post.findByIdAndDelete(req.params.id);

    if (!post) {
      return res.status(404).json({
        status: "fail",
        message: "Post not found",
      });
    }

    res.status(204).json({
      status: "success",
      data: null,
    });
  } catch (error) {
    console.error(error);
    if (error.name === 'CastError') {
      return res.status(400).json({
        status: "fail",
        message: "Invalid post ID format",
      });
    }
    res.status(500).json({
      status: "fail",
      message: "Server Error",
    });
  }
};

postModel.js file code

const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, "Post must have title"],  // Changed from 'require' to 'required'
  },
  body: {
    type: String,
    required: [true, "post must have body"],
  },
});

const Post = mongoose.model("Post", postSchema);
module.exports = Post;

postRoutes.js file code

const express = require("express");
const postController = require("../controllers/postController");

const router = express.Router();

router
  .route("/")
  .get(postController.getAllPosts)
  .post(postController.createPost);

router
  .route("/:id")
  .get(postController.getOnePost)
  .patch(postController.updatePost)
  .delete(postController.deletePost);

module.exports = router;

Install postman. You can watch below video too..
https://youtu.be/Hmn5XeZv-GE?si=WCYtlVSuIclqzEkT

In Postman:
Try making a POST request again with this format in Postman:

URL: http://localhost:3000/api/v1/posts
Method: POST
Headers: Content-Type: application/json
Body:

  • Choose the "Body" tab
  • Select "raw" and choose "JSON" from the dropdown
  • Enter the data in this format:
{
    "title": "Your Post Title",
    "body": "Your Post Content"
}

Now you can comfortably continue with the tutorial without facing any errors.


This content originally appeared on DEV Community and was authored by Sanjeev Saravanan


Print Share Comment Cite Upload Translate Updates
APA

Sanjeev Saravanan | Sciencx (2024-10-22T22:28:57+00:00) Nodejs-Docker YT tutorial updated Code. Retrieved from https://www.scien.cx/2024/10/22/nodejs-docker-yt-tutorial-updated-code/

MLA
" » Nodejs-Docker YT tutorial updated Code." Sanjeev Saravanan | Sciencx - Tuesday October 22, 2024, https://www.scien.cx/2024/10/22/nodejs-docker-yt-tutorial-updated-code/
HARVARD
Sanjeev Saravanan | Sciencx Tuesday October 22, 2024 » Nodejs-Docker YT tutorial updated Code., viewed ,<https://www.scien.cx/2024/10/22/nodejs-docker-yt-tutorial-updated-code/>
VANCOUVER
Sanjeev Saravanan | Sciencx - » Nodejs-Docker YT tutorial updated Code. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/10/22/nodejs-docker-yt-tutorial-updated-code/
CHICAGO
" » Nodejs-Docker YT tutorial updated Code." Sanjeev Saravanan | Sciencx - Accessed . https://www.scien.cx/2024/10/22/nodejs-docker-yt-tutorial-updated-code/
IEEE
" » Nodejs-Docker YT tutorial updated Code." Sanjeev Saravanan | Sciencx [Online]. Available: https://www.scien.cx/2024/10/22/nodejs-docker-yt-tutorial-updated-code/. [Accessed: ]
rf:citation
» Nodejs-Docker YT tutorial updated Code | Sanjeev Saravanan | Sciencx | https://www.scien.cx/2024/10/22/nodejs-docker-yt-tutorial-updated-code/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.