DEV Community

Sanjeev Saravanan
Sanjeev Saravanan

Posted on

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 = 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}`));
Enter fullscreen mode Exit fullscreen mode

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",
    });
  }
};
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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

authController.js file code

const User = require("../models/userModel");

const bcrypt = require("bcryptjs");

exports.signUp = async (req, res) => {
  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",
    });
  }
};
Enter fullscreen mode Exit fullscreen mode

userModel.js file code

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;
Enter fullscreen mode Exit fullscreen mode

userRoute.js file code

const express = require("express");

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

const router = express.Router();

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

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

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 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 = () => {
  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);
app.use("/api/v1/users", userRouter);

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

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

Top comments (0)