node.js - 为什么我的数据无法保存到 MongoDB?
问题描述
我尝试注册,我提交表单然后它记录我undefined
,它不会将用户保存到数据库中,即使教程中的代码也能完美运行。这是我的代码
exports.postSignup = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;
User.findOne({ email: email })
.then(userDoc => {
if (userDoc) {
return res.redirect('/signup');
}
const user = new User({
email: email,
password: password,
cart: { items: [] }
});
return user.save();
})
.then(result => {
res.redirect('/login');
})
.catch(err => {
console.log(err);
});
};
不得不提的是,用户模型是正确的。
解决方案
我不确定,但在我自己的代码中,我没有在返回行中保存对象。
也许试试这个
exports.postSignup = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;
User.findOne({ email: email })
.then(userDoc => {
if (userDoc) {
return res.redirect('/signup');
}
const user = new User({
email: email,
password: password,
cart: { items: [] }
});
try{
user.save();
}catch(err){
res.send(err);
}
return user; //only if you want to return a user ofc
})
其他可能发生的事情:
- 你的ip被列入白名单了吗?
- 您是否包含连接字符串?
- 你返回一个 jason 对象吗?然后确保在中间件中使用解析器。
推荐阅读
- reactjs - React Hooks - 带有钩子的功能组件中 ScrollView 的引用?
- reactjs - React中使用axios删除用户
- javascript - 在 JS 中进行全尺寸跳跃之前,角色会先做一个小跳跃
- r - 将变量的多个值与另一个数据帧的一个值匹配
- android - 当用户注销/关闭应用程序时,是否可以清除 Android 应用程序 RAM 内容?
- mysql - 使用 MySql 管理应用程序访问 Squarespace 数据库
- postgresql - 使用 pgpool 进行 Kubernetes postgres 复制
- javascript - 脚本不显示原始图像
- python - 如何在 python 2.4 中检查 UTF-8 编码数据(字节)
- java - 错误的 requestMapping 通过表单发送