MeWrite Docs

MongooseServerSelectionError: connection refused

MongooseでMongoDBへの接続に失敗した場合のエラー

概要

MongooseがMongoDBサーバーに接続できない場合に発生するエラーです。サーバーが起動していない、接続文字列が間違っている、ネットワークの問題などが原因です。

エラーメッセージ

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
MongoServerError: bad auth : Authentication failed
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined"

解決策

1. 基本的な接続設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import mongoose from 'mongoose'

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGODB_URI!, {
      // Mongoose 6+ではこれらは不要
      // useNewUrlParser: true,
      // useUnifiedTopology: true,
    })
    console.log(`MongoDB Connected: ${conn.connection.host}`)
  } catch (error) {
    console.error('MongoDB connection error:', error)
    process.exit(1)
  }
}

2. 接続文字列の確認

1
2
3
4
5
6
7
8
# ローカル
MONGODB_URI=mongodb://localhost:27017/mydb

# 認証あり
MONGODB_URI=mongodb://username:password@localhost:27017/mydb

# MongoDB Atlas
MONGODB_URI=mongodb+srv://username:password@cluster.xxxxx.mongodb.net/mydb?retryWrites=true&w=majority

3. 接続オプション

1
2
3
4
5
6
7
8
await mongoose.connect(uri, {
  serverSelectionTimeoutMS: 5000,  // サーバー選択タイムアウト
  socketTimeoutMS: 45000,          // ソケットタイムアウト
  maxPoolSize: 10,                 // コネクションプール
  minPoolSize: 5,
  retryWrites: true,
  w: 'majority',
})

4. 接続イベントのハンドリング

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
mongoose.connection.on('connected', () => {
  console.log('Mongoose connected to MongoDB')
})

mongoose.connection.on('error', (err) => {
  console.error('Mongoose connection error:', err)
})

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose disconnected')
})

// グレースフルシャットダウン
process.on('SIGINT', async () => {
  await mongoose.connection.close()
  console.log('Mongoose connection closed due to app termination')
  process.exit(0)
})

5. 再接続ロジック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const connectWithRetry = async () => {
  const maxRetries = 5
  let retries = 0

  while (retries < maxRetries) {
    try {
      await mongoose.connect(process.env.MONGODB_URI!)
      console.log('MongoDB connected')
      return
    } catch (error) {
      retries++
      console.log(`Connection failed. Retry ${retries}/${maxRetries}`)
      await new Promise(resolve => setTimeout(resolve, 5000))
    }
  }

  throw new Error('Failed to connect to MongoDB after retries')
}

6. MongoDB Atlasの設定

1
2
3
4
5
// IP ホワイトリストを確認
// Atlas Dashboard > Network Access > Add IP Address

// 接続文字列の取得
// Atlas Dashboard > Connect > Connect your application

7. Docker環境での接続

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# docker-compose.yml
services:
  app:
    environment:
      - MONGODB_URI=mongodb://mongo:27017/mydb  # コンテナ名を使用
    depends_on:
      - mongo

  mongo:
    image: mongo:7
    ports:
      - "27017:27017"

8. 認証エラーの対処

1
2
3
4
// ユーザー名・パスワードをURIエンコード
const username = encodeURIComponent('user@name')
const password = encodeURIComponent('pass@word!')
const uri = `mongodb://${username}:${password}@localhost:27017/mydb`

9. Mongoose 6+ の変更点

1
2
3
4
5
// strictQuery警告を消す
mongoose.set('strictQuery', true)

// または false(Mongoose 6のデフォルト動作)
mongoose.set('strictQuery', false)

デバッグ

1
2
3
4
5
6
// デバッグモードを有効化
mongoose.set('debug', true)

// 接続状態を確認
console.log('Connection state:', mongoose.connection.readyState)
// 0: disconnected, 1: connected, 2: connecting, 3: disconnecting

関連エラー

関連エラー

MongoDB の他のエラー

最終更新: 2025-12-22