2016-08-19 3 views
0

MongoDB에서 문서 내에 중첩 된 배열 안에 중첩 된 문서를 제거하려고합니다.mongoose를 통해 배열에 중첩 된 문서를 제거하십시오.

스키마

{ 
    "_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); 
     }) 
    }); 
}); 

그것은

array.splice(index, 1); 

스플 라이스의 두 번째 매개 변수는 제거 할 요소의 수입니다 스플 라이스 소개

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

로 변환됩니다 작동합니다. splice는 배열에서 배열을 수정하고 제거 된 요소가 들어있는 새로운 배열을 반환합니다.

+0

이상한. 'undefined'로 설정하지 않았습니다. 올바른 문서를 얻었지만 실제로 설정하지 않았습니다 – 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'과 일치하는 전체 하위 문서를 완전히 제거하는 것입니다. 참조 : "/ 12345/about/1에 DELETE를 보내면"Test Heading 1 "이 포함 된 하위 문서가 완전히 제거됩니다." 기본적으로 (해당 _id 또는 ID 주어진) 문서 내의 배열 (주어진 배열의 이름) 배열에서 항목을 제거 해요. – SlashTag

관련 문제