【问题标题】:How to fix post method error using ExpressJs and MongoDB如何使用 ExpressJs 和 MongoDB 修复 post 方法错误
【发布时间】:2021-02-11 08:06:27
【问题描述】:

我是 Express.js、MongoDb 和 mongoose 的新手,我已经创建了 HTTP 请求方法,但是在运行 Post 方法时,什么都没有做(没有保存在数据库中),并且邮递员仍在加载并且它仅在以下情况下停止我取消。我想知道我的代码有什么问题,谢谢。

    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
})

【问题讨论】:

    标签: node.js mongodb post postman


    【解决方案1】:

    你在这里遗漏了一些东西。 Mongoose 从未在 index.js 中设置,因此没有与数据库的连接。 This should help you follow step by step

    同样在您的路由器中,您发送的没有分配的部门 1。

    如果链接失效或您需要更多信息,请告诉我。

    【讨论】:

    • 与数据库的连接建立,只是我没有共享代码,
    • 请检查您尝试呼叫的路线是否正确。尝试调试代码。
    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 2020-03-26
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多