2017-11-23 6 views
0

나는 여러 개의 주석을 가질 수있는 순간 스키마가 있습니다. 순간이 삭제되면 순간과 관련된 모든 코멘트도 삭제되기를 원합니다.몽구스 - 프리 훅 제거를 사용하여 계단식 삭제하는 방법

MomentSchema

let MomentSchema = new Schema({ 

    body: String, 
    likes: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'User', 
    }], 
    dislikes: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'User', 
    }], 
    comments: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'Comment', 
    }], 
    author: { 
     type: Schema.Types.ObjectId, 
     ref: 'User', 
    }, 

}, 
    { 
     timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}, 
    }); 

MomentSchema.pre('remove', (next) => { 

//What to include here to delete all the comments for this moment 

}); 

참고도 또한 주석 모델이므로 나는 또한 주석 모델의 사전 제거 후크를해야 응답을 가질 수 코멘트?

CommentSchema

let CommentSchema = new Schema({ 

    body: { 
     type: String, 
     required: true, 
    }, 
    moment: { 
     type: Schema.Types.ObjectId, 
     ref: 'Moment', 
    }, 
    author: { 
     type: Schema.Types.ObjectId, ref: 'User', 
     required: true, 
    }, 
    likes: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'User', 
    }], 
    dislikes: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'User', 
    }], 
    parent: { 
     type: Schema.Types.ObjectId, 
     ref: 'Comment', 
    }, 
    replies: [{ 
     type: Schema.Types.ObjectId, 
     ref: 'Comment', 
    }], 

}, 
    { 
     timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}, 
    }); 

API 삭제 : 현재/: ID 내가와 관련된 모든 의견을 삭제하려면 사전 후크에서 삭제해야 할 무엇

destroy(req, res) { 

     let id = req.params.id; 

     Moment.findOne({'_id': id}, (err, moment) => { 

      if (err) { 

       return res.status(404).json({ 

        success: false, 
        status: 404, 
        data: {}, 
        message: 'Failed to find moment', 

       }); 

      } 

      moment.remove((err, moment) => { 

       if (err) { 
        return res.status(400).json({ 
         success: false, 
         status: 400, 
         data: err, 
         message: 'Failed to delete moment', 
        }); 
       } 

       return res.status(200).json({ 

        success: true, 
        status: 200, 
        data: {}, 
        message: 'Successfully deleted moment', 

       }); 

      }); 


     }); 

}

순간. 또한 pre-hook에서 "this"를 호출 할 때 undefined를 반환합니다.

답변

0

모든 코멘트를 제거하려면 & & 다중 캐스케이드 문서에서 .remove 메소드를 호출해야합니다. 아래 코드를 순간 프리 훅 제거 기능에 삽입하면 순간을 제거하기 전에 주석을 삭제합니다.

또한 주석을 제거하기 전에 주석 사전 호출을 호출합니다. 어디 각 코멘트에 대한 답장을 제거하는 코드를 추가 할 수 있습니다. 우리는 한 번만 모든 코멘트가

을 삭제 한 순간을 삭제할로

Comment.find({'moment': this._id}) 
     .then((comments) => { 
      Promise.all(comments.forEach((comment) => comment.remove())) 
       .then(next()); 
     }); 

promise.all 여기에 사용 된