首页 > 解决方案 > 为什么我的数据无法保存到 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);
      });
  };

不得不提的是,用户模型是正确的。

标签: node.jsmongodbauthentication

解决方案


我不确定,但在我自己的代码中,我没有在返回行中保存对象。

也许试试这个

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 对象吗?然后确保在中间件中使用解析器。

推荐阅读