node js express mongoose api save operation not working

I am creating my first node js api using Mongoose and Express. Facing some issue when i try to post the data it does not work. Postman request never completes and data does not get saved. Please find attached code and help me figure out the issue. Also note that db connection gets established successfully.

//Post.js

const mongoose = require("mongoose");

const PostSchema = mongoose.Schema({
  title: {
    type: "string",
    required: true,
  },
  description: {
    type: "string",
    required: true,
  },
  date: {
    type: "Date",
    default: Date.now,
  },
});

module.exports = mongoose.model("Posts", PostSchema);

// Posts.js  => Routes
const express = require("express");
const Post = require("../models/post");
const router = express.Router();

router.get("/", (req, res) => {
  res.send("Posts");
});

router.post("/", (req, res) => {
  try {
    console.log(req.body);

    const post = new Post({
      title: req.body.title,
      description: req.body.description,
    });

    post
      .save()
      .then((data) => res.json(data))
      .catch((err) => res.json(err));
  } catch (error) {
    console.log(error);
  }
});

module.exports = router;

// app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");

//Import Routes
const postRoute = require("./routes/posts");

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

//Routes
app.use("/posts", postRoute);

// Connect to db
mongoose.connect(
  process.env.DB_CONNECTION,
  { useNewUrlParser: true, useUnifiedTopology: true },
  () => {
    console.log("connected to db !");
  }
);

app.listen(3000);


Read more here: https://stackoverflow.com/questions/64950312/node-js-express-mongoose-api-save-operation-not-working

Content Attribution

This content was originally published by Sachin Trivedi at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: