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 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
};
});
});
更新:我已經在這裏加了我搞定。它說:「無法驗證用戶」
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);
});
}
});
是的,我真的想出瞭如何得到問題id。這很簡單。我現在正在努力尋找用戶ID。我如何使用用戶的令牌來做到這一點?目前,用戶登錄。 –
的User.findOne(......之後,你有,你需要從node.js的向下傳遞user._id的角碼的用戶的用戶對象。 –
我已經添加我的GET在上面的問題。它返回「無法驗證用戶」,雖然它顯示在用戶登錄的角度。還'console.log(user);'顯示'null'簡而言之,POST提取用戶,而GET不 –