본문 바로가기

NodeJS/ErrorSolved

Mongo DB 사용 중 database.collection is not a function 에러

NodeJs 코딩 중에 database.collection is not a function 에러가 발생해서 하루를 날렸다.


https://stackoverflow.com/questions/47662220/db-collection-is-not-a-function-when-using-mongoclient-v3-0?rq=1


구글링 해보니 스택오버플로우에 다음과 같이 몽고 디비 2.0 대에서 3.0으로 바뀌면서 드라이버 설정 하는 법이 변경되어서 발생하는 것 같다.


몽고 디비 2.0에서는 

MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
  // Database returned
});


이런 식으로 사용할 DB를 명시해서 사용했었는데 

몽고 디비 3.0에서는 

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});


이런 식으로 바뀐 모양이다.


The close() method has also been moved to the client. The code in the question can therefore be translated to:

MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
}); 

그래서 2.0 버전대 몽고디비를 쓰는 책을 따라하려면 npm install mongodb --save로 모듈을 설치할 때 pakage.json의 내용을 

"dependencies": {
"serve-static": "^1.13.2",
"mongodb": "^2.2.33"
}

위 밑줄 친것처럼 버전대를 2.0으로 수정하고
npm install 실행을 해주면 된다.