无法使用HTTP Put更新MongoDB集合中的对象?

时间:2014-08-02 17:13:27

标签: javascript node.js angularjs mongodb mongoose

我是AngularJS的新手,我正在尝试更新我的MongoDB数据库。当我尝试更新集合中的对象时,我遇到了问题。以下是我尝试这样做的尝试:

//listviewFactory is already injected and returns an event object
//I call $scope.put when clicking (ng-click) on a button

$scope.event = listviewFactory.getEvent();

$scope.put = function(event){
    var currentUser = {};
    if($cookieStore.get('token')) {
        currentUser = User.get();
    }

    event.attendees.push(currentUser);

    $http.post('/api/events/' + event._id, event).success(function(data){
      for(var i = 0; i < event.attendees.length; i++){
        console.log("Attendees: ", event.attendees[i]);
      }

      $location.path('/');
    });

};

我只是不确定为什么我的代码无效。当我执行$http put请求时,我的功能成功并继续执行console.log。当我打印出attendees数组时,我看到currentUser对象确实附加到我的event.attendees数组中。但是,当我使用Mongo shell检查我的数据库时,我的与会者数组未更新并保持空白。关于我可能出错的原因或地点的任何想法?下面也是我的服务器端代码,介绍如何路由我的应用程序并指定如何在MongoDB中存储信息。

module.exports = function(app) {
  app.use('/api/events', require('./api/event'));
  ...
}

module.exports = mongoose.model('Event', EventSchema);
    var express = require('express');
    var controller = require('./event.controller');

    var router = express.Router();

router.get('/', controller.index);
router.put('/:id', controller.update);

// Updates an existing event in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Event.findById(req.params.id, function (err, event) {
    if (err) { return handleError(err); }
    if(!event) { return res.send(404); }
    var updated = _.merge(event, req.body);
    updated.save(function (err) {
      if (err) { return handleError(err); }
      return res.json(200, event);
    });
  });
};

编辑:当我在console.log currentUser:

Current User:  
Resource {$promise: Object, $resolved: false, $get: function, $save: function, $query: function…}
$promise: Object
$resolved: true
__v: 0
_id: "53dd72fb5a24aa781a3cbde8"
email: "test@test.com"
name: "Test User"
provider: "local"
role: "user"

编辑:Mongoose架构:

'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var EventSchema = new Schema({
    startDate: Date,
    endDate: Date,
    eventLocation: String,
    eventName: String,
    attendees: Array
});

1 个答案:

答案 0 :(得分:1)

我假设你正在使用mongoose。试试

updated.markModified('attendees');

前     updated.save致电。

关于推送currentUser,执行与

等效的操作
event.attendees.push({__v: 0
    _id: "53dd72fb5a24aa781a3cbde8"
    email: "test@test.com"
    name: "Test User"
    provider: "local"
    role: "user"})

即只需推送相关字段。