MongoDB文档未保存却显示成功:问卷答案存储问题求助
问题分析与解决方案
先揪出最致命的问题:你的模型定义完全错配了!
在Survey.js里,你定义的是Question Schema,最后导出的是mongoose.model('Question', question),但在Server.js的路由里却用了var survey = new Survey()——这意味着你根本没有正确定义Survey模型,Mongoose找不到对应的集合,自然不会把数据存进MongoDB!
修复步骤:
1. 正确定义Survey模型
修改Survey.js,创建对应问卷答案的Schema,而不是Question的:
var mongoose = require('mongoose'); var Schema = mongoose.Schema; // 定义Survey(问卷答案)的Schema,字段和你提交的参数对应 var surveySchema = new Schema({ name: String, email: String, q_id: String, // 如果q_id是MongoDB的ObjectId类型,就改成mongoose.Schema.Types.ObjectId q_text: String, answer: String // 若答案是多选/复杂类型,可以改成数组或对象 }); // 导出Survey模型 module.exports = mongoose.model('Survey', surveySchema);
然后在Server.js里确保正确引入这个模型:
const Survey = require('./path/to/Survey.js'); // 替换成你的实际文件路径
2. 把PUT请求改成POST请求
PUT方法语义上是更新已有资源,而提交新的问卷答案属于创建新资源,应该用POST:
- 服务器路由修改:
router.route('/answers') .post(function(req, res){ // 把put改成post var survey = new Survey(); survey.name = req.body.name; survey.email = req.body.email; survey.q_id = req.body.q_id; survey.q_text = req.body.q_text; survey.answer = req.body.answer; survey.save(function(err){ if(err){ console.error('保存失败:', err); return res.status(500).send(err); // 给前端返回错误状态码,方便排查 } res.status(201).send(survey); // 201状态码表示资源创建成功,语义更准确 }); })
- 前端axios请求修改:
const url = 'http://localhost:3100/api/answers'; axios.post(url, survey) // put改成post .then(res => { console.log('Successfully posted'); console.log(res); setSubmitting(false); setStatus({submitted: true}); }) .catch(err => { console.error('提交失败:', err); })
3. 额外检查项
- 确认Mongoose已经成功连接到MongoDB,建议在服务器启动时添加连接日志:
mongoose.connect('mongodb://localhost/your-db-name') // 替换成你的数据库名 .then(() => console.log('MongoDB连接成功')) .catch(err => console.error('MongoDB连接失败:', err));
- 可以改用
async/await替代回调函数,让错误处理更清晰:
router.route('/answers') .post(async function(req, res){ try { const survey = new Survey(req.body); // 直接解构req.body,代码更简洁 const savedSurvey = await survey.save(); res.status(201).send(savedSurvey); } catch(err) { console.error('保存失败:', err); res.status(500).send(err); } })
为什么之前服务器能收到数据但不存储?
因为你用了一个不存在的Survey模型(实际导出的是Question),Mongoose在这种情况下可能会静默创建一个无效的模型或者无法找到对应集合,加上你用了语义不符的PUT方法,且没有正确返回错误信息,导致你看不到问题根源。
内容的提问来源于stack exchange,提问作者Anas Shad
相关产品推荐
相关产品推荐

