试图删除mongoose中的嵌套对象

时间:2015-06-28 21:42:09

标签: angularjs node.js mongoose

我试图删除嵌套对象,但出于某种原因,我做错了,因为我似乎无法访问嵌套对象。我可以删除没有嵌套的对象。

这是我的代码

JSON:

{
   "_id": ObjectId("55904d2da35bf71c06184f60"),
   "title": "h1",
   "url": "h1",
   "menuIndex": NumberInt(0),
   "date": ISODate("2015-06-28T21:12:38.256Z"),
   "contents": [
     {
       "order": NumberInt(0),
       "data": "something",
       "_id": ObjectId("55904d38a35bf71c06184f62") 
    },
     {
       "order": NumberInt(1),
       "data": "not something",
       "_id": ObjectId("55904d49a35bf71c06184f63") 
    }
  ],
   "__v": NumberInt(0) 
}

API:

router.post('/content/delete/:id/:contentId', sessionCheck, function(req,res) {
    var id = req.body._id;
    var contentId = req.body._id;
    Page.update({
        _id: id
    }, {
        $pull: {'contents': {
            _id: contentId            
        }}},
        function(err){
            if(err)
                return res.send(err);
        }
    );
});

厂:

.factory('pagesFactory', ['$http', 
  function($http) {

    return {   
       deleteContent: function(id,contentId) {          
          return $http.post('/api/content/delete/'+ id + '/' + contentId);
       }

    };
  }
])

控制器:

$scope.deleteContent = function(id,contentId) {
    pagesFactory.deleteContent(id,contentId);
};

HTML:

<div ng-repeat="data in pageContent.contents track by data.order">
    <button class="btn btn-success" ng-click="deleteContent(pageContent._id,data._id)">Delete</button>
    <div ng-bind-html="trustAsHtml((data.data))">
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

idcontentId都是作为url params而不是POST正文发送的。所以正确的代码是:

var id = req.params.id; // not req.body._id
var contentId = req.params.contentId; // not req.body._id
Page.update({
    _id: id
}, {
    $pull: {'contents': {
        _id: contentId            
    }}},
    function(err){
        if(err)
            return res.send(err);
    }
);