【问题标题】:How to query mongoose for a user with his username如何使用用户名查询 mongoose 的用户
【发布时间】:2016-01-22 06:44:51
【问题描述】:

我的 nodejs API 应用中有这条路线:

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

  var user = {};

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

    if (foundUser) // check the value returned for undefined
    {
      user = foundUser;
    }
  });

  res.json(user);
});

但是这只是返回 {},我确定用户名在数据库中。

这就是我在 Angular 应用程序中调用路线的方式:

$scope.user = function() {
        $http({
            method: 'POST',
            url: "http://groep6api.herokuapp.com/user",
            headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
             //'authentication': 'bearer' + $window.localStorage.getItem('token')
             },
            data: {username: $window.localStorage.getItem('username')},
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            }
        }).success(function (result) {
            console.log(result);
        }).error(function(){

        });
    };

我对 Angular 和 Nodejs 还很陌生,我尝试过 User.find 和 User.findOne,但都没有奏效。如何根据参数在 mongoose 中搜索对象?

【问题讨论】:

  • 你在用护照吗?
  • 无需将其保存在使用数据库的本地存储中...
  • 试试这个:User.findOne({ 'username' : req.body.username },
  • 我很确定你的 if 语句有问题。你能删除 if(foundUser) 我很确定这是问题所在
  • 您的res.json 需要进入查询回调。否则,您将在查询结果可用之前发送响应。

标签: angularjs node.js mongoose


【解决方案1】:

您在 mongoose 调用完成之前返回 json,因此用户变量为空。试试这个:

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

    var user = {};

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

    if (foundUser) // check the value returned for undefined
    {
      user = foundUser;
    }

    res.json(user);
  });

});

【讨论】:

    【解决方案2】:

    您需要将res.json(); 放入您的findOne()

    router.post('/user', function(req, res, next){ if(!req.body.username){ return res.status(400).json({message: 'Geen username'}); } var user = {}; User.findOne({ 'username': req.body.username}, function(err, foundUser){ if(err) return next(err); console.log(foundUser); 
    // if this works everything's fine 
        if (foundUser) // check the value returned for undefined 
    { user = foundUser;  res.json(user); } }); 
         });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 2018-05-08
      相关资源
      最近更新 更多