如何使用ExpressJs和MongoDB修复post方法错误

dwbf0jvd  于 2022-12-26  发布在  Go
关注(0)|答案(2)|浏览(153)

我是Express.js,MongoDb和mongoose的新手,我已经创建了HTTP请求方法,但是当运行Post方法时,什么也没做(数据库中什么也没保存),postman仍然在加载,只有当我取消时才会停止。

router.post("/v1/department", async (req, res) => {
    try {
        const request = req.body
        const department = new Department(request)
        await department.save()
        res.status(200).send(department)
    } catch (error) {
        res.status(500).send(error)
    }
});

这是我的模特

const mongoose = require("mongoose");
const validator = require('validator')

const Department = mongoose.model('Department', {
    name: {
        type: String,
        required: true,
    }
    ,
    email: {
        type: String,
        required: true,
        trim: true,//
        lowercase: true,
        validate(value) {
            if (!validator.isEmail(value)) {
                throw new Error('Invalid email!')
            }
        }
    }
    ,
    createdBy: {
        type: String,
        default: 'SYS_ADMIN'
    }
    ,
    updatedBy: {
        type: String,
        default: 'SYS_ADMIN'
    }
    ,
    createdAt: {
        type: Date
        // ,
        // default: Date.getDate()
    }
    ,
    updatedAt: {
        type: Date
        // ,
        // default: Date.getDate()
    },
    isDeleted: {
        type: Boolean,
        default: false
    }
})

module.exports = Department

这是Index.js

const express = require("express");
const app = express()
const departmentRouter = require("../src/routes/department")

app.use(express.json())
app.use(departmentRouter)

//app.use('/', require('./routes/department'))

const port = process.env.PORT || 5000;//local machine port 3000
app.listen(port, () => (`Server running on local machine port ${port} 🔥`));

与数据库的连接为:

const mongoose = require("mongoose");

//Connect to the local mongoDB database for testing the API localy
mongoose.connect('mongodb://127.0.0.1:27017/openemp-api-department', {
    useNewUrlParser: true,
    useCreateIndex: true
})
u1ehiz5o

u1ehiz5o1#

这里你忽略了一些东西。Mongoose从来没有在index.js中设置过,所以没有到数据库的连接。This should help you follow step by step
同样,在路由器中,您正在发送从未分配的department1。
如果链接不起作用或您需要更多信息,请让我知道。

zpgglvta

zpgglvta2#

对于最新版本的Express,即**(Express v4.16.0及更高版本)**,请在server.js文件中使用此命令:- ————〉

const express = require('express');

app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));

//对于低于4.16.0的Express版本// ---------------------------------

const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

否则您的发布请求将给予您错误(如无法识别任何名称等)****因此请确保根据快速版本使用这些内容x1c 0d1xx 1c 1d 1x
索引.js文件

const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const axios = require("axios");

mongoose.connect(
  "YourMongoUri",
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }
);
const dataSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  age: {
    type: Number,
    required: true,
  },
});
const modelData = mongoose.model("modelData", dataSchema);
router.get("/", (req, res) => {
  modelData.find((err, doc) => {
    if (err) console.log(err.message);
    else {
      res.send(doc);
    }
  });
});
router.post("/", (req, res) => {
  const user = new modelData({
    name: req.body.name,
    age: req.body.age,
  });
  user.save((err, doc) => {
    if (err) return console.log(err);
    res.send(doc);
  });
});
router.put("/:id", (req, res) => {
  const user = modelData.findByIdAndUpdate(
    req.params.id,
    {
      name: req.body.name,
      age: req.body.age,
    },
    (err, doc) => {
      if (err) return console.log(err);
      res.send(doc);
    }
  );
});
router.delete("/:id", (req, res) => {
  modelData.findByIdAndDelete(req.params.id, (err, doc) => {
    if (err) return console.log(err);
    res.send(doc);
  });
});

module.exports = router;

服务器.js文件

const express = require("express");
const myRouter = require("./index");
const app = express();
const port = 3000;
app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);
s;

app.use("/myroute", myRouter);
app.listen(port, console.log("listening on port 3000"));

相关问题