MEAN Stack:如何将函数的结果更新到数据库?

时间:2016-03-20 17:57:44

标签: javascript angularjs node.js mongodb mean-stack

我有一个评论系统,只要点击upvote图标,我就需要将upvotes存储在数据库中。我的功能增加了数量,但是一旦我刷新它,它再次显示0。如何将其直接存储到数据库中? 这是代码:

public / javascripts 目录的 ang.js 中:

var app=angular.module('peopleComments',['ui.router']);
app.factory('comments',['$http', function($http){
var c={
comments:[]
};

//loading all existing comments with getAll()
c.getAll=function(){
return $http.get('/comments').success(function(data){
    angular.copy(data, c.comments);
});
};

//function which creates the new comments for updating in the database
c.create = function(comment) {
return $http.post('/comments', comment).success(function(data){
c.comments.push(data);
});};
return c;
}]);

app.controller('Base',[
'$scope','comments',function($scope,comments){
  $scope.comments=comments.comments;

    $scope.addComment=function(){
        if(!$scope.username||$scope.username==''){$scope.username='Anonymous';}
        if(!$scope.contents||$scope.contents==''){return;}
        comments.create({
            username: $scope.username,
            contents: $scope.contents,
            });
        $scope.username='';
        $scope.contents='';
    }
$scope.increaseUpvotes=function(comment){   //function which updates the upvotes
  comment.upvotes+=1;
}

}]);

1 个答案:

答案 0 :(得分:2)

您需要在服务中创建一个c.update(comment)方法,该方法会更新评论,然后在您的API中调用相应的$http.put()方法,以便在点击upvote按钮时更新评论。

更新:还有一个潜在问题 - 如果您没有专门创建comment.upvotes属性并默认将其设置为0,那么您的comment.upvotes += 1可能会向null添加一个{1}}或undefined并没有真正添加一个。