平均堆栈:如何将函数的结果更新到数据库

MEAN Stack: How to update a function's result to the database?

本文关键字:结果 更新 数据库 函数 堆栈      更新时间:2023-09-26

我有一个评论系统,每当单击赞成图标时,我都需要将赞成票存储在数据库中。我拥有的函数增加了数字,但一旦我刷新它,它就会再次显示 0。如何将其直接存储到数据库中?这是代码:

ang.jspublic/javascripts 目录中:

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;
}
}]);
您需要

在服务中创建一个c.update(comment)方法,该方法接受要更新的注释,然后在单击 upvote 按钮时调用 API 中的相应 $http.put() 方法来更新注释。

更新:另一个潜在问题 - 如果您没有专门创建 comment.upvotes 属性并将其默认设置为 0,那么您comment.upvotes += 1可能会将一个添加到nullundefined,而不是真正添加一个。