我正在尝试对mongodb进行一些操作,
当我摆脱异步等待时,我得到了200条代码,但没有保存在数据库上,我认为这是正常的,并且在异步代码中,当我在邮递员上测试我的路由时,得到了“服务器无响应”错误。
>/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);
我看不到我在做什么错,我仍然是新手,不胜感激!
答案 0 :(得分:1)
问题在于,当我第一次放置:等待约会.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 !'});
答案 1 :(得分:1)
它一定是您的mysql中的错误,由于您没有处理该错误而未显示,请替换为:
await appointment.save().catch(function(err){ console.log(err)}))
并查看其打印内容。您还返回“保存到数据库”,而不检查保存是否成功,也没有将其保存到变量中