在Nuxt3中使用DocumentDB(MongoDB)的方法

由于在Nuxt3的服务器上连接AWS的DocumentDB遇到了一些困难,所以我将分享一种在我的环境中成功运行的方法。

规格

在本地连接MongoDB,在AWS上连接DocumentDB。

本地环境:Docker、MongoDB、Nuxt3
AWS云平台:ECS Fargate、DocumentDB、Nuxt3

代码

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文件放置

请使用TLS进行认证以支持DocumentDB。
将rds-combined-ca-bundle.pem文件放置在公共目录中。
具体下载方法如下所示。

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

最后

TLS认证花了好长时间…

广告
将在 10 秒后关闭
bannerAds