NodeJs giving TypeError that Post is not a constructor

I am working on NodeJs application. I am trying to save posts in database and I am getting this error after making a post request from postman.

** <pre>TypeError: Post is not a constructor**
**warnings--
(node:6704) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new 
Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(node:6704) DeprecationWarning: Listening to events on the Db class has been deprecated and will be removed in the next major version.**

post schema

const mongoose=require('mongoose')

const Post_Schema=mongoose.Schema({
    title:{
        type:String,
        required:true
    },
    description:{
        type:String,
        required:true
    },
    date:{
        type:Date,
        default:Date.now()  
    }
});
exports.module=mongoose.model('Posts',Post_Schema)

post.js

const express=require('express')
const router=express.Router();

const Post=require('../../models/Post')
router.post('/',(req,res)=>{
    //creating new post with our 'POST MODEL'
    const post=new Post({
        title:req.body.title,
        description:req.body.description

    });
    //saving in DB
    //post.save() return a promise
     post.save()
     .then(data=>res.json(data))
     .catch(err=>res.json({msg:err}))
}
)



module.exports=router

app.js

const express=require('express');
const app=express();
const PORT=process.env.PORT || 5000
const mongoose=require('mongoose');
// const cors=require('cors')
require('dotenv/config')

app.use(express.json());
app.use(express.urlencoded({extended:'false'}))
// app.use(cors())
//init middleware
app.use('/posts',require('./routes/api/posts'))


//connect to DB
mongoose.connect(process.env.DB_CONNECTION,
{ useNewUrlParser: true },{ useUnifiedTopology: true },
()=>console.log('connected to DB!'))

app.listen(PORT,()=>{
    console.log(`Server is running at port ${PORT}`)
})

1 thought on “NodeJs giving TypeError that Post is not a constructor”

  1. use Post instead of Posts because mongoose add s to the name of collection automatically

    exports.module=mongoose.model('Post',Post_Schema)
    

    Note when you want connect to the database passing this option {useUnifiedTopology: true} so just try like this

    mongoose.connect(process.env.DB_CONNECTION, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useUnifiedTopology: true,
      })
      .then(() => {
        console.log("connected to DB!");
        app.listen(PORT, () => {
          console.log(`Server is running at port ${PORT}`);
        });
      })
      .catch((error) => {
        console.log(error);
      });
    
    Reply

Leave a Comment