문제상황:
Node.js를 사용하여 웹 서버를 개발하고, 다음과 같은 코드를 작성하여 데이터베이스에 접근하려고 했습니다.
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/myDatabase';
mongoose.connect(connectionString);
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', err => {
console.log('Error connecting to MongoDB:', err);
});
// 실행 코드...
그러나 다음과 같은 에러로그가 발생했습니다.
(node:12345) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Connection failed
해결방법:
다음과 같이 코드를 수정하여 에러를 해결했습니다.
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/myDatabase';
mongoose.connect(connectionString)
.then(() => {
console.log('Connected to MongoDB');
})
.catch(err => {
console.log('Error connecting to MongoDB:', err);
});
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', err => {
console.log('Error connecting to MongoDB:', err);
});
// 실행 코드...
원인분석:
이 에러는 Promise가 reject 상태로 종료되었지만, 이를 처리하는 코드가 없어 발생합니다. 기존 코드에서는 mongoose.connect() 함수가 Promise를 반환하나, 에러가 발생했을 때 이를 처리하는 catch 구문이 없었습니다. 해결 방법으로 수정된 코드에서는 then()과 catch()를 사용하여 Promise가 정상적으로 처리되거나 에러가 발생했을 때 적절한 처리를 할 수 있도록 구현했습니다.
참고링크:
Mongoose: Connecting to MongoDB
[Mongoose v7.0.3: Connecting to MongoDB
You can connect to MongoDB with the mongoose.connect() method. mongoose.connect('mongodb://127.0.0.1:27017/myapp'); This is the minimum needed to connect the myapp database running locally on the default port (27017). If connecting fails on your machine, t
mongoosejs.com](https://mongoosejs.com/docs/connections.html)
[Process | Node.js v19.8.1 Documentation
Process# Source Code: lib/process.js The process object provides information about, and control over, the current Node.js process. import process from 'node:process';const process = require('node:process'); Process events# The process object is an instance
nodejs.org](https://nodejs.org/api/process.html#process_event_unhandledrejection)