2017-08-17 43 views
0

你好,我正試圖從我的模型中用Mongoose中移除一個數組,並且它似乎不起作用。我想從collectionImages中刪除一個對象。這裏是我的代碼:Mongoose從Schema中刪除對象arr

架構

var CollectionSchema = mongoose.Schema({ 
    collectionName: String, 
    collectionImages: [ 
     { 
      imageName: String, 
     } 
    ], 
    path: String 
}); 

刪除方法:

router.delete("/collection/:id/:imageId", function (req, res) { 
    var imageId = req.params.imageId; 

    Collections.findById(req.params.id, function (err, collections) { 
     if (err) { 
      console.log(err); 
     } else { 

      for (var i = 0; i < collections.collectionImages.length; i++) { 
       if (collections.collectionImages[i]._id == imageId) { 
        var checkedImageId = collections.collectionImages[i]._id; 
        collections.collectionImages[i].splice(imageId,1); 
       }; 
      } 

     } 
     ; 
    }); 
}); 

形式:

<form id="deleteForm" action="/collection/<%= collections._id %>/<%= image._id %>?_method=DELETE" method="post"> 
        <button class="fa fa-minus-circle">Delete</button> 
       </form> 
+0

@尼爾·倫恩是的,我看到它是相同的,但alsow有提供的解決方案這麼想的工作對我來說。我希望有更多expertience可以幫助我 – Adrian

回答

1

請嘗試以下

Collections.update(
    { _id: req.params.id }, 
    { $pull: { 'collectionImages': { '_id': req.params.imageId } } } 
).exec(function (err, user) { 
    if (err) { res.status(500).send(err); return; } 
    res.send(); 
}); 

更多閱讀this

+0

Hy @nmanikiran我試過我沒有得到500錯誤,但對象仍然存在。 – Adrian

+0

它的工作,我不得不改變路由器和_method PUT。坦克@nmanikiran – Adrian