2017-12-28 8 views
1

나는 완전히 Mongoose으로 붙어있어 제거 방법입니다. 의견과 양식이있는 페이지가 Delete입니다. 내 목표는 클릭 한 댓글 만 삭제하는 것입니다. 아래는 내 MongoDB 파일입니다 (덧붙여서 나는 express 라이브러리의 override 메서드를 사용하여 요청 게시와 삭제를 모두 처리합니다).Mongo 내의 배열에서 요소를 제거하는 방법



{ 
    "_id": { 
     "$oid": "5a455cf460414f548f3d1afb" 
    }, 
    "title": "Tets", 
    "body": "tes", 
    "user": { 
     "$oid": "5a440bae124b7e4626aeeb70" 
    }, 
    "date": { 
     "$date": "2017-12-28T21:07:00.194Z" 
    }, 
    "comments": [ 
     { 
      "commentBody": "ets", 
      "commentUser": { 
       "$oid": "5a440bae124b7e4626aeeb70" 
      }, 
      "_id": { 
       "$oid": "5a455cf660414f548f3d1afc" 
      }, 
      "commentDate": { 
       "$date": "2017-12-28T21:07:02.143Z" 
      } 
     } 
    ], 
    "allowComments": true, 
    "status": "public", 
    "__v": 1 
} 

내 스키마



     const mongoose = require('mongoose') 
     const Schema = mongoose.Schema; 

     //Create Schema 
     const StorySchema = new Schema({ 
     title: { 
      type: String, 
      required: true 
     }, 
     body: { 
      type: String, 
      required: true 
     }, 
     status: { 
      type: String, 
      default: 'public' 
     }, 
     allowComments: { 
      type: Boolean, 
      default: true 
     }, 
     comments: [{ 
      commentBody: { 
       type: String, 
       required: true 
      }, 
      commentDate: { 
       type: Date, 
       default: Date.now 
      }, 
      commentUser: { 
       type: Schema.Types.ObjectId, 
       ref: 'users' 
      } 
     }], 
     user: { 
      type: Schema.Types.ObjectId, 
      ref: 'users' 
     }, 
     date: { 
      type: Date, 
      default: Date.now 
     } 
    }); 

     mongoose.model('stories',StorySchema, 'stories'); 

그리고 내 JS 파일은 내 게시물의 방법은 내가 원하는하지만 전혀 작동하지 않습니다 삭제

을 (속성을 읽을 수 없습니다 정의의 '코멘트') 정확히 어떻게 작동 여기


    router.post('/comment/:id' , (req , res) => { 
    Story.findOne({ 
     _id: req.params.id 
    }) 
    .then(story => { 
     const newComment = { 
      commentBody: req.body.commentBody, 
      commentUser: req.user.id 
     } 

     //Push to comments array 
     story.comments.unshift(newComment); 

     story.save() 
     .then(story => { 
      res.redirect(`/stories/show/${story.id}`) 
     }) 
    }); 
    }) 

    router.delete('/comment/:id', (req, res) => { 
    Story.remove({ 
     _id: req.body.id.comments 
    }) 
    .then(() => { 
     req.flash('success_msg', 'Comments Removed!'); 
     res.redirect('/dashboard'); 
    }) 
    }); 

내 핸들은 양식 파일입니다

{{#each story.comments}}

<form action="/stories/comment/{{id}}?_method=DELETE" method="post" id="delete-form"> 
<input type="hidden" name="_method" value="DELETE"> 
<button type="submit" class="btn red"><i class="fa fa-remove"></i> Delete</button> 
</form> 

{{/each}} 
,536,913 63,210

오류가 나는

TypeError: Cannot read property 'comments' of undefined 
at router.delete (/Users/ar2z/Desktop/fierce-caverns-70427/routes/stories.js:197:20) 

이 제발 도와 얻었다. 나는 완전히 잃어 버렸다.

+1

보내 주신 요청을 표시하십시오. 오류는 요청 본문에 "id"객체가 없다는 힌트를 제공합니다. – Christian

답변

0

실제로 최근에 동일한 오류가 발생했습니다. 내가 배열 요소 같은 방식으로 일을하려고 할 때 내가



    Story.remove({ 
      _id: req.body.id.comments 
     }) 

코드 위 몽고 개체 함께 일하고 있어요으로

router.delete("/comments/:id", function(req,res){ 
    var Model = require("myModel"); 
    //Run a find and update query to delete the comment 
    Model.findOne({_id:req.params.id}, function(err,doc){ 
     if(doc && !err){ 
     doc.comments = doc.comments.filter(function(comment){ 
      //This will filter out the comment you want to delete 
      return comment._id != req.body.commentId 
     }) 
     } 
     res.redirect("/comments/") 
    }) 
} 
+0

도움을 주셔서 대단히 감사합니다. 불행히도 "doc"이 의미하는 방식대로 작동하지 않습니다. –

+0

''doc'는'findOne' 메소드에 의해 발견 된 문서입니다. 그런 다음 필드에 액세스하여 수정하고 마지막으로 변경된 복사본을 저장할 수 있습니다. – Andy

+0

고맙습니다. Andy, 알겠습니다. –

0

내 잘못은 처음부터 있었다 : 나는 당신이이 작업을 수행 할 필요가 발견 이 배열에서 삭제 요소 개체 만 위해 일하고 배열 요소에 대해 작동하지 않습니다 내가 사용



Story.update({ }, { $pull: { comments: { _id: req.params.id }}}, { multi: true }) 

이 코드는 문서

의 배열에서 항목 제거

$pull MongoDb documentation

관련 문제