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

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

从 post-man 以 json 格式 posting api 时出现此错误,

我正在创建一个用于学习目的的 MEAN 应用程序并遇到此错误,请帮助我解决此错误

也从 Whosebug 尝试了许多类似的东西,但没有帮助。 还从 Whosebug 尝试了许多类似的东西,但没有帮助。

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;

试试这个。

const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    name : {type: String},
    position : {type: String},
    dept : {type: String},
});

const Employee = mongoose.model('Employee', schema);
 
module.exports = Employee;

您在 employee.js 文件中编写的代码存在一些问题。

  1. mongoose.model() 需要名称和架构。您传递了正确的名称,但随后传递了一个简单的对象而不是 new mongoose.Schema({})。您可以按照其他答案中提到的更新架构,或者使用 new mongoose.Schema({}).

    更新内联对象
  2. 应该是module.exports不是module.export.

除了建议之外,您还可以从依赖项中删除 body-parser。因为,Express 已经有了。只写 -

app.use(express.json())