使用Mongoose的Contact.create无法写入MongoDB,newContact返回null
问题分析与修复方案
核心问题
你的代码里**Contact.create()没有传入要存储的数据对象**,反而在then回调里单独写了({name:req.body.name, phone:req.body.phone})——这行代码只是创建了一个临时对象,根本没有传递给Mongoose的创建方法,所以数据库不会写入任何数据,newContact自然是null。
修复后的代码
app.post('/create-contact', function(req, res) { // 把要创建的文档数据作为参数传给Contact.create() Contact.create({ name: req.body.name, phone: req.body.phone }).then(function(newContact) { console.log('*******************', newContact); return res.redirect('back'); }).catch(function(err) { console.log("Error in creating the contact!", err); // 打印错误详情,方便排查问题 return res.redirect('back'); // 错误时也需给客户端返回响应,避免请求挂起 }); });
额外优化提示
catch回调不需要第二个参数newContact,Mongoose的create方法的catch仅接收错误对象- 建议添加
req.body数据合法性校验,比如判断name和phone是否存在,避免写入无效空数据
内容的提问来源于stack exchange,提问作者Debmalya Mukherjee
相关产品推荐
相关产品推荐

