在mongodb更新记录

时间:2015-07-22 08:31:27

标签: angularjs node.js

我有一个文件名Musicians.js,其中包含:

exports.update = function(req, res) {
  var id = req.params.id;
 console.log("ID-->" + id);  //I GET CORRECT ID HERE

  var updates = req.body;
//It does not update any records
      Musician.update({"_id":id}, req.body, 
        function (err, numberAffected) {
          if (err) return console.log(err);
          console.log('Updated %d musicians', numberAffected);  //gives 0 updated musicians
          return res.send(202);


      });
    };

routes.js

app.put('/musicians/:id', musicians.update);

我称之为:

$scope.updateTodo = function(id) {
        console.log("INSIDE UPDATE TO DO");
        console.log(id); 
        $scope.navMode = 'updateMusician';
        $scope.getOneTodo(id,function(data){
                var x=data;
                console.log("X" + x);
        $scope.formData.name= x.name;
        $scope.formData.band = x.band;
        $scope.formData.instrument = x.instrument;
        });
        $http.put('/musicians/' + id)
            .success(function(data) {
              $scope.todos = data;
                console.log("UPDATED||||||||||||||||||||||||||||||||||||||");
                      console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });


    };

我得到0个响应更新。

可能有什么不对?为什么即使匹配ID也不会更新记录?

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

请试试这个:

exports.update = function(req, res) {
  var Musician = req.musician;

  Musician = _extend(Musician, req.body);

  Musician.save(function (err, numberAffected) {
      if (err) {
        console.log(err);
        return;
      }
      console.log('Updated %d musicians', numberAffected);
      res.jsonp(Musician);
    });
};

如果没有,请尝试更改:

var Musician = req.musician;

到此:

var Musician = req.Musician;

如果这有帮助,请告诉我。