使用NodeJS将数据保存到MongoDB

时间:2019-06-20 15:37:57

标签: javascript reactjs mongodb express mongoose

我正在尝试将数据传递到MongoDB集合,并且它返回Cannot POST /courseweb/course/add

在通过axios传递值之前,我尝试过postman(一种Google扩展名)来发送数据。

这是我的server.js,它是通过expressjs实现的

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const Bundler = require("parcel-bundler");
const cors = require("cors");
const mongoose = require("mongoose");

const InstructorDB = require('./public/DBModels/InstructorDB');

const router = express.Router();

const bundler = new Bundler("./src/index.html");

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bundler.middleware());
// app.use(express.static('./src'));

app.use("/courseweb", router);

mongoose.connect("mongodb://127.0.0.1:27017/courseweb", {
  useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", () => {
  console.log("Connected to MongoDB via 27017");
});

app.listen(3000, err => {
  if (err) {
    console.error(err);
    process.exit(-1);
  }
  console.log("Application is running on port 3000");
});

app.get("/", function(req, res) {
  res.sendFile("./dist/index.html");
});

router.route('/course/add').post((req, res) => {
  let instructorDB = new InstructorDB(req.body);
  instructorDB.save().then(bookDB => {
    res.status(200).send(`${bookDB} Added`);
  }).catch((err) => {
    res.status(400).send({message: err});
  });
});

router.route('/courses').get((req, res) => {
  // name of the course database model here
  InstructorDB.find().count(function(err, count){
    res.status(200).send(count);
});
});

这是我的InstructorDB.js,是mongoose的模式模型

const mongoose= require('mongoose');
const Schema = mongoose.Schema;

let InstructorDB = new Schema({
    firstName: String,
    lastName: String,
    designation: String,
    faculty: String,   
    contactNumber: Number,
    email: String,
    password: String,
    isEnabaled: Boolean,
    courses: [{courseID: String}]
});

module.exports = mongoose.model('InstructorDB', InstructorDB, 'InstructorDB');

这是屏幕截图,是我通过postman传递值时得到的响应。我也将标头设置为content-typeapplication/json

screenshot

谁能告诉我我哪里出问题了?

2 个答案:

答案 0 :(得分:0)

如果要将路由器放入同一文件中,则不需要路由器。

改为尝试以下语法:

app.post('/coureweb/course/add',((req, res) => {
  let instructorDB = new InstructorDB(req.body);
  instructorDB.save().then(bookDB => {
    res.status(200).send(`${bookDB} Added`);
  }).catch((err) => {
    res.status(400).send({message: err});
  });
}));

然后取出

app.use("/courseweb")

答案 1 :(得分:0)

确保通过邮寄请求发送正确的数据,并将动词更改为post

app.post('/course/add', (req, res) => {

  if(req.body == null){

    return res.status(400).send({message: 'bad request'});

  }

  let instructorDB = new InstructorDB(req.body);

  instructorDB.save((err ,doc ) => {
    if(err){
    res.status(400).send({message: err});

   }
    res.status(200).send(`Added`);
  });

});