node.js - 更新 Mongoose 中的对象会导致循环

标签 node.js mongodb express mongoose

在我的 Nodejs API 应用程序中,我有以下路线:

router.post('/startuserseries', function(req, res, next){
  if(!req.body.username){
    return res.status(400).json({message: 'Geen username'});
  }

  User.findOne({ 'username': req.body.username}, function(err, foundUser){
    if(err)
      return next(err);

    if (foundUser) // check the value returned for undefined
    {
      foundUser.isdoingchallenges = true;
      foundUser.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
      });
    }
  });

});

当我在 postman 中调用这条路由时,请求永远不会结束。 我尝试过使用 PUT 但也不起作用,我尝试了各种代码结构但都不起作用。

最佳答案

此请求将无法完成,因为它没有在服务器上写入响应命令。

您应该像下面这样轻松解决这个问题:

router.post('/startuserseries', function(req, res, next){
  if(!req.body.username){
    return res.status(400).json({message: 'Geen username'});
  }

  User.findOne({ 'username': req.body.username}, function(err, foundUser){
    if(err)
      return next(err);

    if (foundUser) // check the value returned for undefined
    {
      foundUser.isdoingchallenges = true;
      foundUser.save(function (err) {
        if(err) {
           res.json(err);
        }
      });
    }
    res.send(200);
    // or your specific result json object
    // res.json({"error":false,"message":"completed"})
  });

});

关于node.js - 更新 Mongoose 中的对象会导致循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33395936/

相关文章:

node.js - 向 Mean.io 初学者解释 Mean.io 示例包的身份验证如何工作

javascript - "Transaction not found"当使用 Bambora 捕获支付交易时

javascript - 使用 Bower 优于 Git 子模块的好处

c# - 使用 LINQ 和 MongoDb 重新创建位置数组运算符

javascript - 从对象数组中删除元素

css - ExpressJs : using Navbar on views

javascript - Node.js - 在使用 Express 时未定义端口时停止应用程序

node.js - 如何在 sequelize 中创建模型之间的关联

node.js - 使用嵌套循环对返回响应进行序列化

javascript - Mongo 会处理我的服务吗?