mongodb.connect() 메서드란?
mongodb.connect()는 Node.js 애플리케이션과 MongoDB 서버를 연결할 때 사용하는 메서드입니다. 이 메서드는 MongoDB 모듈에서 제공되는 비동기(asynchronous) 방식으로 동작하며, 데이터베이스 서버에 접속한 후 콜백 함수를 통해 결과를 처리합니다.
문법(Syntax)
mongodb.connect(path[, callback])
매개변수(Parameters)
- path – 실제로 MongoDB 서버가 실행 중인 서버 경로와 포트 번호를 의미합니다. 예를 들어
mongodb://localhost:27017/형태로 작성합니다. - callback – 연결 과정에서 오류가 발생하거나 연결이 완료되었을 때 호출되는 콜백 함수입니다.
MongoDB 설치 및 환경 설정
Node.js 애플리케이션과 MongoDB를 연결하기 전에, 먼저 MongoDB 서버 환경을 준비해야 합니다. 아래 단계를 순서대로 따라 해 보세요.
1. npm으로 MongoDB 드라이버 설치
다음 명령어를 사용해 npm에서 MongoDB 패키지를 프로젝트에 설치합니다.
npm install mongodb --save
2. 로컬 MongoDB 서버 실행
아래 명령어를 실행하면 지정한 localhost 서버에서 MongoDB가 구동됩니다. 이 과정을 통해 애플리케이션과의 연결 준비가 완료됩니다.
mongod --dbpath=data --bind_ip 127.0.0.1
3. 연결 코드 작성 및 실행
MongodbConnect.js파일을 생성하고, 아래 예제 코드를 복사해 붙여넣습니다.- 그다음 다음 명령어로 코드를 실행합니다.
node MongodbConnect.js
예제 코드(Example)
// 필요한 MongoDB 모듈 불러오기
const MongoClient = require("mongodb");
// 서버 경로
const url = 'mongodb://localhost:27017/';
// 데이터베이스 이름
const dbname = "Employee";
MongoClient.connect(url, (err, client) => {
if (!err) {
console.log("서버와 성공적으로 연결되었습니다");
} else {
console.log("연결 중 오류가 발생했습니다");
}
})실행 결과(Output)
C:\Users\tutorialsPoint\> node MongodbConnect.js
(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-deprecation ...` to show where the warning was created)
successful connection with the server.참고 사항
실행 결과에 표시된 DeprecationWarning은 기존 서버 탐색 엔진이 더 이상 권장되지 않는다는 경고 메시지입니다. 최신 MongoDB 드라이버 버전에서는 자동으로 새로운 엔진이 적용되므로 대부분의 경우 무시해도 무방하지만, 경고를 제거하고 싶다면 연결 옵션에 { useUnifiedTopology: true }를 추가하면 됩니다.