오늘은 컴퓨터에 몽고DB를 설치하는데 하루를 보냈다.
첫 난관은 몽고DB를 설치한 뒤에 data 폴더와 경로를 연결하는 곳에서 마주했다. 다만 이건 그냥 내가 헛발질 한거라서 인터넷 찾아보고 경로 잘 설정해서 해결.
두 번째 난관은 기본 설정을 마치고 테스트 시동을 할 때 발생했다.
db에서 사용하는 find()나 save() method에서 에러가 발생했는데 error 메시지를 살펴보니 "no longer accept a callback."이었나 이런 식으로 떴었다.
검색해서 요지를 살펴보니 내가 몽고DB를 설치하려고 검색했던 예제 페이지에서는 mongoDB에서 데이터 등을 가져오거나 삽입할 때 callback함수를 설정해서 데이터를 조작했는데 mongoDB 최신 버전에서는 callback함수를 지원하지 않는다는 것이었다. callback 대신에 promise를 사용하거나 async/await 문법을 사용하라고 나와있었다.
(테스트 중이었어서 오류 페이지 스샷을 따로 찍어놓지는 않았다.)
// 원래 코드
Student.find(function(error, students){
console.log('--- Read all ---');
if(error){
console.log(error);
}else{
console.log(students);
}
});
위에서 find method가 mongoDB의 collection에서 데이터를 가져오는 method이다. 원래 코드의 경우 find method 안에 익명 함수로 콜백 함수가 설정된 상태였는데, mongoDB 최신 버전에서는 이렇게 callback 함수를 사용하는 걸 더 이상 지원하지 않는다고 한다.
// 수정 코드 (async / await 활용)
Student.find(async function(error, students){
await console.log('--- Read all ---');
if(error){
console.log(error);
}else{
console.log(students);
}
});
// 수정 코드 (promise 활용)
Student.find()
.then(function(error, students){
console.log('--- Read all ---');
if(error){
console.log(error);
}else{
console.log(students);
}
});
그래서 위의 코드와 같이 코드를 수정해주면 정상적으로 동작하더라.
mongoDB를 nodejs에서 사용하기 위해서는
terminal에서 기본적인 연결 세팅을 모두 마친 후에,
npm install mongodb
npm을 통해 mongodb 패키지를 설치해준다.
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
let database;
async function connect() {
const client = await MongoClient.connect('mongodb://localhost:27017');
database = client.db('blog');
}
function getDb() {
if(!database) {
throw {message: 'Database connection not established!'}
}
return database;
}
module.exports = {
connectToDatabase: connect,
getDb, getDb,
}
위의 코드가 기본 세팅인데, 맨 아래에 module.exports로 빼주고 있는 것은 위의 코드를 메인 js파일이 아니라 db용 js파일로 분리해서 보통 사용하기 때문이다.
메인이 되는 main.js 파일에서
const db = require('./data/database');
const authors = db.getDb().collection('authors').find().toArray();
위와 같은 방법으로 db와 관련된 js 파일을 import하여 사용한다.