如何为 Mongoose 连接设置 TLS

How can I set TLS for Mongoose connection

我正在尝试将我的 mongo 数据库从 Compose 迁移到 IBM Cloud Databases for Mongo 和他们的文档(https://www.compose.com/articles/exporting-databases-from-compose-for-mongodb-to-ibm-cloud/):“With a new Databases for MongoDB 部署,您将获得两个端点的副本集以连接到您的数据库。MongoDB 的数据库也使用 TLS 证书,因此您需要配置 Mongo接受两个主机和一个 TLS 证书的 DB 应用程序驱动程序

如何在 Mongoose 连接中设置 IBM Cloud 提供的 TLS 证书? 我试过的都没有用:(

如果我使用 IBM cli,我可以看到我的数据库,但是我无法从我的 node.js 应用程序连接到它

var mongoose = require('mongoose');
mongoose.Promise = Promise;
var uri="mongodb://admin:passSftgdsdfvrrdfs@host1-1231243242.databases.appdomain.cloud:32605,host2-1231243242,host1-1231243242/testDatabaseName?authSource=admin&replicaSet=replset"
myDb.db = mongoose.createConnection(uri, {
  tls: true,
  tlsCAFile:`076baeec-1337-11e9-8c9b-ae5t6r3d1b17` (this is the name of the certificate and is placed in the root)
  // tlsCAFile: require('fs').readFileSync('041baeec-1272-11e9-8c9b-ae2e3a9c1b17') // I have also tried something like this

绝对没有任何工作,即使数据库在那里 请帮助我

尝试以下操作:


var key = fs.readFileSync('/home/node/mongodb/mongodb.pem');
var ca = [fs.readFileSync('/home/node/mongodb/ca.pem')];

var o = {
    server: {
        ssl: true,
        sslValidate:true,
        sslCA: ca,
        sslKey: key,
        sslCert:key
    },
    user: '****',
    pass: '****'
};

m.connect('mongodb://dbAddr/dbName', o)```

我也遇到了同样的问题 这对我有用

 mongoose.connect(‘mongodb+srv://username:password@host/db_name?authSource=admin&replicaSet=repliasetname&tls=true&tlsCAFile=/root/ca-certificate.crt’,{some config})

我是本地做的,需要先安装隧道

$ ssh -i "IF YOU HAVE PEM.pem" -L <27017:YOUR_AMAZON_HOST:27017> <server_user_name@server_ip_OR_server_url> -N

我设法实现如下

const CERTIFICATE_PATH = 'rds-combined-ca-bundle.pem'
const certificateCA = CERTIFICATE_PATH && [fs.readFileSync(CERTIFICATE_PATH)];
    
const sslOptions = certificateCA
  ? ({
      ssl: true,
      tlsAllowInvalidHostnames: true,
      sslCA: certificateCA,
      user: MONGODB_USER,
      pass: MONGODB_PASSWORD,
    } as ConnectionOptions)
  : {};

const options: ConnectionOptions = {
  ...sslOptions,
};

export const connectMongoDb = async (): Promise<void> => {
  await mongoose.connect('mongodb://localhost:27017/test', options);
  console.log(' Successfully connected to the database');
};

您需要设置

MONGODB_USER

MONGODB_PASSWORD