<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sanjeev Saravanan</title>
    <description>The latest articles on DEV Community by Sanjeev Saravanan (@sanjeev_saravanan_27).</description>
    <link>https://dev.to/sanjeev_saravanan_27</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2215692%2F059e13dd-8c71-43ca-aca4-f4559a6fd43f.jpg</url>
      <title>DEV Community: Sanjeev Saravanan</title>
      <link>https://dev.to/sanjeev_saravanan_27</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sanjeev_saravanan_27"/>
    <language>en</language>
    <item>
      <title>Nodejs-Docker YT tutorial updated Code</title>
      <dc:creator>Sanjeev Saravanan</dc:creator>
      <pubDate>Tue, 22 Oct 2024 22:28:57 +0000</pubDate>
      <link>https://dev.to/sanjeev_saravanan_27/nodejs-docker-yt-updated-code-3peo</link>
      <guid>https://dev.to/sanjeev_saravanan_27/nodejs-docker-yt-updated-code-3peo</guid>
      <description>&lt;h2&gt;
  
  
  CRUD APPLICATION CODE
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;index.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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 = () =&amp;gt; {
  mongoose
    .connect(mongoURL)
    .then(() =&amp;gt; console.log("Successfully connected to Database"))
    .catch((e) =&amp;gt; {
      console.log("Error connecting to DB:", e);
      setTimeout(connectWithRetry, 5000);  // Retry after 5 seconds
    });
};

connectWithRetry();

app.get("/", (req, res) =&amp;gt; {
  res.send("&amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;");
});

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

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

app.listen(port, () =&amp;gt; console.log(`Listening on port ${port}`));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;postController.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Post = require("../models/postModel");

// Get all posts
exports.getAllPosts = async (req, res, next) =&amp;gt; {
  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) =&amp;gt; {
  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) =&amp;gt; {
  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 =&amp;gt; ({
          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) =&amp;gt; {
  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 =&amp;gt; ({
          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) =&amp;gt; {
  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",
    });
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;postModel.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;postRoutes.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Install postman. You can watch below video too..&lt;br&gt;
&lt;a href="https://youtu.be/Hmn5XeZv-GE?si=WCYtlVSuIclqzEkT" rel="noopener noreferrer"&gt;https://youtu.be/Hmn5XeZv-GE?si=WCYtlVSuIclqzEkT&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In Postman:&lt;br&gt;
Try making a POST request again with this format in Postman:&lt;/p&gt;

&lt;p&gt;URL: &lt;a href="http://localhost:3000/api/v1/posts" rel="noopener noreferrer"&gt;http://localhost:3000/api/v1/posts&lt;/a&gt;&lt;br&gt;
Method: POST&lt;br&gt;
Headers: Content-Type: application/json&lt;br&gt;
Body:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Choose the "Body" tab&lt;/li&gt;
&lt;li&gt;Select "raw" and choose "JSON" from the dropdown&lt;/li&gt;
&lt;li&gt;Enter the data in this format:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "title": "Your Post Title",
    "body": "Your Post Content"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Now you can comfortably continue with the tutorial without facing any errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;authController.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const User = require("../models/userModel");

const bcrypt = require("bcryptjs");

exports.signUp = async (req, res) =&amp;gt; {
  const { username, password } = req.body;

  try {
    const hashpassword = await bcrypt.hash(password, 12);
    const newUser = await User.create({
      username,
      password: hashpassword,
    });
    res.status(201).json({
      status: "success",
      data: {
        user: newUser,
      },
    });
  } catch (e) {
    res.status(400).json({
      status: "fail",
    });
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;userModel.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, "User must have a username"],
    unique: true,
  },
  password: {
    type: String,
    required: [true, "User must have a password"],
  },
});

const User = mongoose.model("user", userSchema);

module.exports = User;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;userRoute.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");

const authController = require("../controllers/authController");

const router = express.Router();

router.post("/signup", authController.signUp);

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;index.js&lt;/strong&gt; file code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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 userRouter = require("./routes/userRoutes");

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 = () =&amp;gt; {
  mongoose
    .connect(mongoURL)
    .then(() =&amp;gt; console.log("Successfully connected to Database"))
    .catch((e) =&amp;gt; {
      console.log("Error connecting to DB:", e);
      setTimeout(connectWithRetry, 5000);  // Retry after 5 seconds
    });
};

connectWithRetry();

app.get("/", (req, res) =&amp;gt; {
  res.send("&amp;lt;h1&amp;gt;Hello World&amp;lt;/h1&amp;gt;");
});

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

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

app.listen(port, () =&amp;gt; console.log(`Listening on port ${port}`));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
  </channel>
</rss>
