2016-08-19 86 views
0

我試圖刪除嵌套在MongoDB中嵌套在文檔中的數組內嵌的文檔。通過貓鼬刪除嵌套在數組中的文檔

架構

{ 
    "_id": 12345, 
    "id": 12345, 
    "name": "Test", 
    "links": [], 
    "training": [], 
    "about": [ 
    { 
     "contents": "Test Contents 0", 
     "heading": "Test Heading 0" 
    }, 
    { 
     "contents": "Test Contents 1", 
     "heading": "Test Heading 1" 
    }, 
    { 
     "contents": "Test Contents 2", 
     "heading": "Test Heading 2" 
    } 
    ] 
} 

我想刪除該路由

'/:_id/:section/:item' 

這樣的,如果我發送匹配的子文檔一個DELETE/12345/about/1,含有「測試標題1」的分商務部將被完全刪除。

我已經嘗試了很多不同的方法,如

.delete(function (req, res) { 
    var section = req.params.section_name; 
    var item = req.params.item; 

    Tool.findOne({'id': req.params._id}, function (err, tool) { 
     tool.set(section[item], null); 
     tool.save(function (err) { 
      res.send(err); 
     }) 
    }); 
}); 

但似乎沒有工作。

任何幫助將不勝感激。

回答

1

這應該很好地工作

.delete(function (req, res) { 
    var section = req.params.section_name; 
    //convert string to int 
    var item = +req.params.item; //or use parseInt(req.params.item) 

    Tool.findOne({'id': req.params._id}, function (err, tool) { 
     tool[section].splice(item, 1); 
     tool.save(function (err) { 
      res.send(err); 
     }) 
    }); 
}); 

它轉化爲

tool[section].splice(item, 1); 
tool.about.splice(1, 1); //remove 1 item from given index 

關於拼接

array.splice(index, 1); 

拼接的第二個參數是元素刪除的數量。請注意,拼接會在適當位置修改數組並返回一個包含已被移除的元素的新數組。

+0

奇怪。它不會將其設置爲「未定義」。它正在得到正確的文件,但它並沒有真正設置它 – SlashTag

+0

嘗試使用'splice',我已經更新了答案 –

+0

YES!這工作。謝謝! – SlashTag

0
Tool.findOneAndUpdate(
{ 
    "_id": req.params._id, "about.heading": "Test Heading 1" 
    // 1. query above will target the document by _id. 
    // 2. search [about] and get index then store it at "$", 
    // 3. "Test Heading 1" is located at about[1], store it at "$" 
    // 4. imagine this line is executed => var $ = 1 
}, 
{ 
    $unset: {"about.$": 1} 
}, 
{ 
    new:true //means return the updated document (new instead old) 

}) 
.exec((err, tool)=>{ 
    if(err) console.log(err) 
}) 
+0

也許我並不清楚,但我的意圖是完全刪除與'/ id/section/item'匹配的整個子文檔。請參閱:「如果我將DELETE發送到/ 12345/about/1,則包含」測試標題1「的子文檔將被完全刪除。」 基本上,我在文檔中刪除了一個數組(給定一個索引)的數組(給定了數組的名稱)(給定了它的_id或id) – SlashTag