[node.js] MongoDB find/aggregate 대량 document 가져올 때 MongoNetworkError: cursor killed or timed out 발생시
node.js 2020. 5. 27. 15:14
node.js에서 MongoDB native driver인 node-mongodb-native 사용시,
find/aggregate 결과 가져오는 document가 많을 경우 cursor 레벨에서 아래와 같은 에러가 높은 확률로 발생했다.
MongoNetworkError: cursor killed or timed out
document 가져오는 방식을 forEach(), toArray() 뭘로 해도 동일했고,
find()의 2번째 파라메터에 timeout:true 설정하거나 cursor의 addCursorFlag('noCursorTimeout', true) 혹은 maxTimeMS()를 설정하는 등 timeout 관련 설정 등을 해도 동일한 결과가 나왔다.
결론은 무슨 수를 쓰든 에러가 발생할 수 있으므로 그냥 에러가 안날 때 까지 재차 요청하는 방식으로 해결하는 수 밖에 없다는 것.
현재까지는.
const MongoClient = require('mongodb').MongoClient;
(async()=>{
// client 연결
const client = await MongoClient.connect(CONNECTION_STRING, OPTIONS);
// DB
const db = client.db(DB_NAME);
// collection
const collection = db.collection(COLLECTION_NAME);
// query 요청
const q = { ... };
const opt = { ... };
const MAX_RETRY = 10;
const cursor = await collection.find(q, opt);
let r = null;
let qErr = null;
for (let i=0; i<MAX_RETRY; i++) {
qErr = null;
try {
r = await cursor.toArray();
} catch (e) {
// 문제 발생시 재시도
qErr = e;
cursor.rewind();
continue;
}
break;
}
// 에러
if (qErr !== null) {
console.log(qErr);
}
// 정상
else {
console.log(r);
}
})();
'node.js' 카테고리의 다른 글
[node.js] WriteStream 사용시 fd close (0) | 2021.07.12 |
---|---|
[node.js] http/https로 application/x-www-form-urlencoded POST로 request (0) | 2021.06.03 |
[node.js] load average throttle (0) | 2019.09.26 |
[node.js] 동시에 실행되는 수를 조절하며 비동기 함수 전체 실행 (Promise.all with limited concurrency) (0) | 2019.09.26 |
[node.js] cluster worker와 동기식(sync) 통신하기 (synchronous communication with cluster workers) (0) | 2019.06.26 |