2017-06-16 53 views
0

我使用mongodb作爲我的project here,但我不確定如何將ObjectId從角度發佈到節點後端。我看到問題_id GET,但不知道如何將它送回到POST。我沒看到。 API中的req.body需要問題和員工_id才能使用mongodb。Mongodb + Angularjs:如何從角度發佈_id到服務器

<h1 class="question capitalize">{{answer.question}}</h1><br> 
 
<a class="btn btn-ghost" ng-click="yes(answer)" href="#">Yes</a>

(function() { 

"use strict"; 

angular 
    .module("feedback") 
    .controller("feedbackCtrl", function($scope, $http, Auth){ 
     if (Auth.isLoggedIn()){ 
      Auth.getUser().then(function(data){ 
       $scope.answer = {}; 
       $http.get('/feedback').then(function(response){ 
        $scope.answer.question = response.data.title; 
       }); 

       $scope.yes = function(info) {     
        $scope.answer.question = info.question; 
        $scope.answer.response = 'Yes'; 
        $scope.answer.username = data.data.username; //from auth 
        $http.post('/feedback', $scope.answer).then(function(response) { 
         console.log(response); 
        }); 
       }; 

      }); 
     } 
     else { 
      console.log('Failure: User is NOT logged in'); 
     } 
    }); 

})(); 

API

router.post('/', function (req, res) { 
    User.findOne({ username: req.body.username }).exec(function(err, user) { 
     if(err) throw err; 

     if(!user) { 
      res.json({ success: false, message: 'Could not authenticate user' }) 
     } else if (user){ 
       Answer.findOneAndUpdate({ 
          question: req.body.question, 
          employee: req.body.username 
         }, 
         req.body, 
         { 
          upsert: true //updates if present, else inserts 
         }) 
       .exec(function(err, answer) { 

       }); 
       console.log('entry saved to answer >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'); 
     }; 
    }); 
}); 

enter image description here

enter image description here

更新:我已經在這裏加了我搞定。它說:「無法驗證用戶」

router.get('/', function(req, res){ 
    User.findOne({ username: req.body.username }).exec(function(err, user) {  
     console.log(user); 
     if(err) throw err; 

     if(!user) { 

      res.json({ success: false, message: 'Could not authenticate user' }) 
     } else if (user) { 

      // continue with processing, user was authenticated 
      token = jwt.sign({ username: user.username }, secret, { expiresIn: '24h'}); 

      res.json({ success: true, message: 'User authenticated', token: token }); 

       Question.findOne({ title:"Should we buy a coffee machine?" }) 
         .exec(function (err, docs){ 
         console.log(docs); 
         res.json(docs); 
       }); 
     } 
    }); 

回答

1

您需要從響應對象在複製_id到$ scope.answer對象。你應該改變你的代碼:

$scope.answer.question = response.data.title; 
$scope.answer._id = response.data._id; 
+0

是的,我真的想出瞭如何得到問題id。這很簡單。我現在正在努力尋找用戶ID。我如何使用用戶的令牌來做到這一點?目前,用戶登錄。 –

+0

的User.findOne(......之後,你有,你需要從node.js的向下傳遞user._id的角碼的用戶的用戶對象。 –

+0

我已經添加我的GET在上面的問題。它返回「無法驗證用戶」,雖然它顯示在用戶登錄的角度。還'console.log(user);'顯示'null'簡而言之,POST提取用戶,而GET不 –

相關問題