복붙노트

[MONGODB] 몽구스에서 삭제 캐스케이드 스타일

MONGODB

몽구스에서 삭제 캐스케이드 스타일

MySQL의 외래 키를 사용하는 것과 유사 몽구스의 부모의 모든 자식을 삭제하는 방법이 있나요?

예를 들어, MySQL은 내가 외국 키를 할당 것 및 삭제에 계단식으로 설정합니다. 나는 클라이언트를 삭제한다면 따라서, 모든 응용 프로그램과 연결된 사용자도 제거 될 것이다.

최상위 수준에서 :

경품 및 제출은 모두 CLIENT_ID위한 필드가 있습니다. 제출은 sweepstakes_id 및 CLIENT_ID 모두를위한 필드가 있습니다.

지금, 나는 다음과 같은 코드를 사용하고 있는데 나는 더 나은 방법이 있어야한다 생각합니다.

Client.findById(req.params.client_id, function(err, client) {

    if (err)
        return next(new restify.InternalError(err));
    else if (!client)
        return next(new restify.ResourceNotFoundError('The resource you requested could not be found.'));

    // find and remove all associated sweepstakes
    Sweepstakes.find({client_id: client._id}).remove();

    // find and remove all submissions
    Submission.find({client_id: client._id}).remove();

    client.remove();

    res.send({id: req.params.client_id});

});

해결법

  1. ==============================

    1.이 몽구스의 '삭제'미들웨어의 주요 사용 사례 중 하나입니다.

    이 몽구스의 '삭제'미들웨어의 주요 사용 사례 중 하나입니다.

    clientSchema.pre('remove', function(next) {
        // 'this' is the client being removed. Provide callbacks here if you want
        // to be notified of the calls' result.
        Sweepstakes.remove({client_id: this._id}).exec();
        Submission.remove({client_id: this._id}).exec();
        next();
    });
    

    당신은 () client.remove를 호출 할 때이 방법이 미들웨어는 자동으로 종속성을 정리하기 위해 호출됩니다.

  2. ==============================

    2.경우 귀하의 참조는 클라이언트가 다음 허용 대답과 유사한 방법으로 당신이 submissionSchema에 다음을 정의 할 수 있습니다, submission_ids의 배열을 가지고, 말, 주변의 다른 방법으로 저장되어 있습니다 :

    경우 귀하의 참조는 클라이언트가 다음 허용 대답과 유사한 방법으로 당신이 submissionSchema에 다음을 정의 할 수 있습니다, submission_ids의 배열을 가지고, 말, 주변의 다른 방법으로 저장되어 있습니다 :

    submissionSchema.pre('remove', function(next) {
        Client.update(
            { submission_ids : this._id}, 
            { $pull: { submission_ids: this._id } },
            { multi: true })  //if reference exists in multiple documents 
        .exec();
        next();
    });
    

    어떤이 submission.remove에 고객의 참조 배열로부터 제출의 ID를 제거합니다 ().

  3. ==============================

    3.여기에 다른 방법 I의 FOUND입니다

    여기에 다른 방법 I의 FOUND입니다

    submissionSchema.pre('remove', function(next) {
        this.model('Client').remove({ submission_ids: this._id }, next);
        next();
    });
    
  4. from https://stackoverflow.com/questions/14348516/cascade-style-delete-in-mongoose by cc-by-sa and MIT license