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);
}


})();

 

 

 

Posted by bloodguy
,