NodeJs Middleware无法正常工作以避免重复数据提交

时间:2017-11-12 11:40:34

标签: javascript node.js mongodb express mongoose

我编写了一个中间件,以避免重复提交相同的数据。它似乎阻止了重复,但它不提交新数据。我收到错误“无法在发送后设置标头”。是否有任何方法可以用来防止这种情况发生?

中间件

function checkDuplication(req, res, next) {
  if (req.isAuthenticated()) { // is user logged in?

    User.findById(req.params.id, function(err, foundUser) {
      if (err) {
        res.redirect('back');
        console.log(err);
      } else {

        for (var index = 0; index < foundUser.friendRequest.length; index++) {
          if ((foundUser.friendRequest[index].id.toString()) ===
            (req.user._id.toString())) {
            console.log("you are already in his friends list ");
            break;
          } else { //so is there is any way that I can only run this line 
            //once outside the loop and avoid several response by express

            console.log("one friend added");
            next();
          }
        }
        res.redirect("back");
      }
    })
  } else {
    res.redirect('back');
  }
}

//Post route to submit a data
router.post("/people/friendRequest/:id", checkDuplication,
  function(req, res) {

    User.findById(req.params.id, function(err, user) {
      if (err) {
        throw err;
      } else {
        var Request = {
          id: req.user._id,
          username: req.user.username
        }

        user.friendRequest.push(Request);
        user.save();

        res.redirect("back"); //getting error due this line
      }
    })
    res.redirect("back");
})

1 个答案:

答案 0 :(得分:0)

您可以使用数组函数来检查是否有符合条件的项目:

if (foundUser.friendRequest.some((fr) => fr.id.toString() === req.user._id.toString())) {
    console.log("you are already in his friends list ");
    res.redirect("back");
} else {
    next();
}

这将查看数组,直到找到匹配为止,此时它将调用`res.redirect(&#34; back&#34;)。

如果找不到匹配项,则会调用next()