问题描述
我正在将mongodb用于我的在此进行项目,但是我不确定如何将ObjectId
从角度发布到节点后端.我在 GET 中看到了问题_id,但不确定如何通过 POST 发回.我没看到. api中的req.body
要求同时提供问题和员工_id才能与mongodb一起使用.
I'm using mongodb for my project here but I am unsure of how to post ObjectId
's from angular to the node backend. I see the question _id in the GET but not sure how to send it back in POST. I do not see it. The req.body
in api requires both question and employee _id's to work with mongodb.
<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 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
};
});
});
更新:我已经在这里添加了我的信息.上面写着无法验证用户身份"
UPDATE: I've added my get here. It says "Could not authenticate user"
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从响应对象复制到$ scope.answer对象.您应该将代码更改为:
You need to copy the _id over from the response object to the $scope.answer object. You should change your code to:
$scope.answer.question = response.data.title;
$scope.answer._id = response.data._id;
这篇关于Mongodb + Angular.js:如何将_id从Angular发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!