1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nuxt3でDocumentDB(MongoDB)を使う方法

Posted at

Nuxt3のserverで、AWSのDocumentDBに接続するのに手間取ったので、私の環境でうまく行った方法を公開します。

仕様

以下のようにローカルでは、MongoDBに接続し、AWSではDocumentDBに接続する。

ローカル:Docker, MongoDB, Nuxt3
AWS:ECS Fargate, DocumentDB, Nuxt3

コード

server/database.ts
import mongoose from 'mongoose';
import fs from 'fs';
import path from 'path';

const connection: {
  isConnected: any;
  db: mongoose.Connection | undefined;
} = {
  isConnected: false,
  db: undefined,
};

async function connectDB() {
  if (connection.isConnected) {
    return connection.db;
  }

  let db = undefined;
  console.log('connecting');
  const username = encodeURIComponent(process.env.MONGODB_USERNAME || '');
  const password = encodeURIComponent(process.env.MONGODB_PASSWORD || '');
  const host = process.env.MONGODB_HOST;
  if (process.env.IS_DEV) {
    db = await mongoose.connect(`mongodb://${host}/`, {
      "authSource": "admin",
      "user": username,
      "pass": password,
    });
  } else {
    const caBundlePath = path.resolve(process.cwd(), './public/rds-combined-ca-bundle.pem');
    try {
      db = await mongoose.connect(`mongodb://${username}:${password}@${host}/`, {
        tls: true,
        sslValidate: true,
        tlsCAFile: caBundlePath,
        replicaSet: 'rs0',
        readPreference: 'secondaryPreferred',
        retryWrites: false,
      });
      console.log('MongoDB Connected');
    } catch (err) {
      console.log('MongoDB Connection Error: ', err);
    }
  }
  if (!db) return;
  console.log('connected');
  connection.isConnected = db.connections[0].readyState;
  connection.db = db.connections[0].useDb('YOUR_DB_NAME');
  return connection.db;
}

export default connectDB;

pemファイル設置

DocumentDBは、TLSで認証しているので、その対応をする。
publicディレクトリに rds-combined-ca-bundle.pem を設置する。
ダウンロード方法は以下の通り。

$ wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem

最後に

TLS認証でめちゃくちゃ時間かかった。。。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?