【问题标题】:How do I notify users, that they have entered dupilcate entry如何通知用户,他们输入了重复条目
【发布时间】:2021-10-15 15:03:57
【问题描述】:

我正在使用 mongodb 来存储详细信息。我知道已经有人问过这个问题,但解决方案对我不起作用。

const userSchema = {
  email: {type: String, unique: true},
  password: String
};

我使用了我在上面输入的模式,它有点工作,我的意思是,它不会让重复的条目被插入到数据库中。但是我遇到的问题是,它没有出现任何错误,所以我无法使用以下代码。

if(err){
  console.log("Repeated record");
}

由于没有错误,页面继续加载,大约 2-3 分钟,最后显示“页面不工作,localhost 没有发送任何数据。”有人可以让我知道我应该采取什么方法来实现这一目标。

编辑:这是服务器代码:

app.get("/", function(req, res){
  res.render("home");
});

app.get("/login", function(req, res){
  res.render("login");
});

app.get("/register", function(req, res){
  res.render("register");
});

app.post("/register", function(req, res){
  const newUser = new User({
    email: req.body.username,
    password: req.body.password
  });
  newUser.save(function(err){
    if(err){
      console.log(err);
    }else{
      res.render("login");
    };
  });
});

app.post("/login", function(req, res){
  const username = req.body.username;
  const password = req.body.password;
  User.findOne({email: username}, function(err, foundUser){
    if(err){
      console.log(err);
    }else{
      if(foundUser){
        if(foundUser.password == password){
          res.sendFile(__dirname + "/public/upload.html");
        }
      }
    }
  });
});

我已经安装了 express、body-parser 和 ejs。主页、登录和注册是扩展名 .ejs 的模板。

谢谢。

【问题讨论】:

  • 您在哪里检查重复项?在上面的代码sn-p中找不到
  • @novonimo 我没有检查重复,但我使电子邮件在模式中是唯一的。 const userSchema = { email: {type: String, unique: true}, password: String };

标签: javascript node.js mongodb express web-deployment


【解决方案1】:

如果发生错误或其他情况,您必须向客户端发送响应。否则你的函数不会发送任何数据。我在您的代码中添加了一些注释行,标记为--> Here。在这些函数中使用res.send()res.render() 将响应发送到您的客户端。

另外添加状态码可能有助于理解错误码(只是建议)。

app.post("/register", function(req, res){
  const newUser = new User({
    email: req.body.username,
    password: req.body.password
  });
  newUser.save(function(err){
    if(err){
      console.log(err);
      // res.status(422).send(err) or res.render(errorPage) --> Here
    }else{
      res.render("login");
    };
  });
});

app.post("/login", function(req, res){
  const username = req.body.username;
  const password = req.body.password;
  User.findOne({email: username}, function(err, foundUser){
    if(err){
      console.log(err);
      // res.status(500).send(err) or res.render(errorPage); --> Here 
    }else{
      if(foundUser){
        if(foundUser.password == password){
          res.sendFile(__dirname + "/public/upload.html");
        } else {
          // res.status(401).send('Some error message') res.render(errorPage); --> And here
        }
      }
    }
  });
});

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2017-03-04
    • 2018-02-07
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多