Search code examples
node.jsmongodbexpressmean-stackmean.io

"TypeError: Employee is not a constructor" while building a MEAN app


Getting this error while posting api from post-man in json format,

i am creating a MEAN app for learning purpose and facing this error, please help me to solve this error

also tried many similar things from stackoverflow but didnt help. also tried many similar things from stackoverflow but didnt help.

db.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/meanDB',{ useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true}, (err)=> {
    if(!err){
        console.log('Database connection successful')
    }
    else{
        console.log('Error in connection' + err)
    }
})

module.exports = mongoose;

package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.12.7"
  }
}

index.js

const app = express();
app.use(bodyParser.json());

app.use(cors({origin:'http://localhost:4200'}));

app.listen(3000, () => console.log ('Hi server started at port: 3000'));

app.use('/employees', routes);

employee.js

const mongoose = require('mongoose');

const Employee = mongoose.model  ('Employee', {
    name : {type: String},
    position : {type: String},
    dept : {type: String},
});

 

module.export = Employee ;

routes.js

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

const Employee = require('../models/employee.js');

//Post api
router.post('/',  (req, res) => {
  let emp =new Employee  ({
    name: req.body.name ,
    position: req.body.position,
    dept: req.body.dept,
  });

  emp.save((err, doc) => {
    if (err) {
      console.log("Error in post data" + err);
    } else {
      res.send(doc);
    }
  });
});

module.exports = router;

Solution

  • There are couple of problems with the code you have written in employee.js file.

    1. mongoose.model() requires name and the Schema. You passed the correct name but then you passed a simple object instead of new mongoose.Schema({}). You can either update the schema as mentioned in the other answer or update the inline object with new mongoose.Schema({}).

    2. It should be module.exports not module.export.

    Apart from this as suggestion, you can also remove body-parser from the dependency. Because, Express has it already. Just write -

    app.use(express.json())