在平均堆栈中更新mongodb

时间:2016-11-29 10:31:58

标签: javascript angularjs node.js mongodb

我想更新我的mongodb我知道在服务器端写什么,但我不知道如何在客户端以角度使用它。你能帮我吗 ? 这是我的服务器端代码

module.exports.updateUser = function (req, res) {
// get a user with ID of 1
User.findById(1, function(err, user) {
  if (err) throw err;

  // change the users location
  user.location = 'uk';

  // save the user
  user.save(function(err) {
    if (err) throw err;

    console.log('User successfully updated!');
  });

});
}

1 个答案:

答案 0 :(得分:0)

您需要创建一个rest api(/ users / save)

 var users =  require('./src/servies/users');
    app.post('/users/save', users.updateUser);

将调用您的updateUser函数。 在角度你可以使用http模块,如下面的代码

<script>
    var app = angular.module("app", []);
    app.controller("HttpPostController", function ($scope, $http) {

        $scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON 
            var data = $.param({
                location: $scope.location
            });

            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            // calling post /users/save api from angular code 
            $http.post('/users/save', data, config)
            .success(function (data, status, headers, config) {

            })
            .error(function (data, status, header, config) {

            });
        };

    });
</script>
相关问题