2014-06-12 3 views
1

모델의 배열에 반복하여 데이터를 찾을 수 :몽구스는 : 내가 비동기 알고리즘에 갇히지있어

var allRefDatasSchemas = { 
    RefAllotement: mongoose.model('RefAllotement', RefDataSchema), 
    RefModeleConstructeur: mongoose.model('RefModeleConstructeur', RefDataSchema), 
    RefTypeKit: mongoose.model('RefTypeKit', RefDataSchema), 
    RefTypeUtilisation: mongoose.model('RefTypeUtilisation', RefDataSchema), 
}; 

내가 잡아 싶습니다

나는 몽구스 모델의 배열을했습니다 각 컬렉션의 모든 항목을 배열이나 그 안에 넣으십시오. 내가 그렇게 할 경우 나 모델 항목 나는 또한 성공하지 async 라이브러리를 시도했습니다

var results = {}; 

for (var model in allRefDatasSchemas) { 

    allRefDatasSchemas[model].find(function(err, data) { 

    // I'd like to do something like that : 
    // but this.modelName is null, because it isn't the model 
    // on which the find is done. 
    results[this.modelName] = data; 

    // if I use "model" variable, it doesn't work, because asynchronous callback 

    }); 

} 

에 속하는 아는 는 find 콜백의 this 키워드는 그래서 불가능 현재 모델, 참조하지 않습니다 왜냐하면 나는 항상 같은 문제로 돌아 가기 때문에 어떤 모델이 콜백 내부에서 찾기 쿼리를 실행 하는지를 알 수 없다. 약속을 사용하는 경우 Idem은 then입니다.

제발 도와주세요. 어떻게할까요?

EDIT model.find는 query.find, query.find는 mquery.find를 호출합니다. mquery.find에서 그 시점에서이 참조를 잃어 콜백이 호출됩니다. this._collection.find (conds, options, utils.tick (callback)); /EDIT

+0

당신은 정보를 추가하기보다는 의견을 게시하기 위해 자신의 질문을 편집 할 수있을 것입니다. 나는 확실히 당신이 다른 방식으로 모델을 만들 수 있기 때문에 왜 이것을하고 싶은지 이해하지 못합니다. 그러나 'async' 시리즈는 게시자가 게시 한 코드가 아니라는 점을 제외하고는 효과가 있습니다. –

+0

네, 모델링에 대한 귀하의 질문을 이해합니다 : 내 목표는 백본 클라이언트 응용 프로그램에서 한 번에 일부 refdata (선택한 입력에 사용되는 데이터)를로드하는 것입니다 ([패턴] (http://ricostacruz.com/backbone -patterns/# bootstrapping_data)) :) – Etienne

답변

3

이 코드 스 니펫을 확인하십시오. 필자는 필요한 샘플을 작성했습니다. 더 나은 이해를 위해 코드의 주석을 확인하십시오.

Sample Working code과 비슷합니다. mongoose와 비동기 사용을위한 또 다른 ref ques.

/* 
* Object to store all models 
*/ 
var allRefDatasSchemas = { 
    RefAllotement: mongoose.model('RefAllotement', RefDataSchema), 
    RefModeleConstructeur: mongoose.model('RefModeleConstructeur', RefDataSchema), 
    RefTypeKit: mongoose.model('RefTypeKit', RefDataSchema), 
    RefTypeUtilisation: mongoose.model('RefTypeUtilisation', RefDataSchema), 
}; 
/* 
* need an array to run all queries one by one in a definite order using async waterfall mwthod 
*/ 
var arr = []; 
for(each in allRefDatasSchemas) { 
    arr.push(each); 
} 

/* 
* Callback function for initiation of waterfall 
*/ 
var queue = [ 
    function(callback) { 
     // pass the ref array and run first query by passing starting index - 0 
     callback(null, arr, 0) 
    } 
]; 

/* 
* Object to store result of all queries 
*/ 
var finalResult = {}; 

/* 
* Generic Callback function for every dynamic query 
*/ 
var callbackFunc = function(prevModelData, currentIndex, callback) { 
    allRefDatasSchemas[arr[currentIndex]].find(function(err, result) { 
     if(err) { 
      console.log(err) 
     } else { 

      // Your Query 
      // 
      // I'd like to do something like that : 
      // but this.modelName is null, because it isn't the model 
      // on which the find is done. 

      // arr[currentIndex] will point to 
      // RefAllotement, RefModeleConstructeur etc. as you required 
      finalResult[arr[currentIndex]] = result 

      // send current result to next interation if required or you can skip 
      // and increment the currentIndex to call next query 
      callback(null, result, currentIndex + 1) 
     } 
    }) 
} 

/* 
* Add callback function for every dynamic query 
*/ 
for(each in allRefDatasSchemas) { 
    queue.push(callbackFunc); 
} 

/* 
* Run all dynamic queries one by one using async.js waterfall method 
*/ 
async.waterfall(queue, function (err, result) { 
    // Final object with result of all the queries 
    console.log('finish', finalResult) 
}); 

출력이 형식

finish { RefAllotement:[ 
     // Result of RefAllotement query 
    ], 
    RefModeleConstructeur:[ 
     // Result of RefModeleConstructeur query 
    ], 
    RefTypeKit:[ 
     // Result of RefTypeKit query 
    ], 
    RefTypeUtilisation:[ 
     // Result of RefTypeUtilisation query 
    ] 
} 
+0

놀라워요! 제가 놓친 유일한 것은 인덱스 된 모델의 이름으로 두 번째 배열을 만드는 것입니다! 그것과 함께 find 콜백에서 modelName을 알 수 있습니다 ('finalResult [arr [currentIndex]] = result'). 분명한 답변을 보내 주셔서 감사합니다. – Etienne

+0

당신 덕분에, 내 첫 번째 질문 StackOverflow에서 허용 –

관련 문제