【问题标题】:200status but collection remains empty200status 但集合仍然为空
【发布时间】:2019-11-05 19:00:57
【问题描述】:

我正在尝试在 mongodb 上进行一些 crud 操作,

当我摆脱异步等待时,我得到了 200 代码,但没有任何东西保存在 db 上,我猜这是正常的,当我在邮递员上测试我的路由时,使用异步代码我得到“服务器无响应”错误。

/routes.js

const router = require('express-promise-router')();
const appointmentController =require ('../controllers/appointments');


router.get('/list',appointmentController.list);
router.post('/add',appointmentController.add);


module.exports = router

/controllers.js

const Appointment = require("../models/Appointment");

module.exports = {
    list: async (req, res) => {
    const appointment =  await Appointment.find();
    res.send({appointment});
     },
   add: async (req, res) => {
   const appointment = new Appointment(req.body);
   await appointment.save();
   return res.status(200).json('saved to the db !');

  },

 };

/模型:

 const appointmentSchema = new Schema({
 Neurologist: {type: String, required: true},
 Remarks: String,
 Date: { type: Date, required: true },
 Hour: { type: Number, required: true },
 Type: {type: String, required: true}
});
 const Appointment = mongoose.model("appointment", appointmentSchema);

我看不出我做错了什么,我还是个新手,任何帮助将不胜感激!

【问题讨论】:

  • 您可以添加模型以便我们提供帮助吗?
  • @zardilior 我的错,我刚刚更正了文件名:-)

标签: mongodb express postman


【解决方案1】:

一定是你的mysql有错误,因为你没有处理错误,所以没有显示,替换为:

await appointment.save().catch(function(err){ console.log(err)}))

然后看看它打印了什么。您还返回“保存到数据库”而不检查保存是否成功,也不将其保存到变量中

【讨论】:

  • 你能测试一下吗?
【解决方案2】:

问题是,当我第一次输入 : await 约会.save() 时,它导致了服务器超时。所以这部分代码是错误的,这解释了为什么当我摆脱异步时,我可以获得代码 200,但没有任何东西进入数据库。实际上 req.body 没有时间发送。这部分代码应该是异步的。

add: async (req, res) => {
const appointment =  await new Appointment(req.body);
appointment.save();
return res.status(200).json({message:'cool saved to the db !'});

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多