'How to fix this MongoClient connection?
I'm trying to connect a node.js app (written in TS) to MongoDB at Yandex Cloud. I have successfully connected there via mongosh
:
mongosh "mongodb://<user>:<pass>@<host>:<port>/?replicaSet=<rs>&authSource=<db>&ssl=true" \
--tls --tlsCAFile ./YandexInternalRootCA.crt
where YandexInternalRootCA.crt is the downloaded certificate. Now I'm trying to do the same via MongoClient
like this (the code is adapted from their examples; node v15.14.0, mongodb ^4.1.2):
import { MongoClient, Db } from 'mongodb'
import fs from 'fs'
const connnectionString = '<same connection string as the above argument of mongosh>'
const options = {
useNewUrlParser: true,
replSet: {
sslCA: fs.readFileSync('./YandexInternalRootCA.crt')
},
//tlsInsecure: true,
}
const getStorage = async (): Promise<Db> => {
// ts-ignore here is due to some typing problem: once you use 2 arguments
// in .connect, TS shows that it promises void (which is not true)
// @ts-ignore
return (await MongoClient.connect(connnectionString, options)).db()
}
Unexectedly, this results in
MongooseServerSelectionError: self signed certificate in certificate chain
I've tried to add tlsInsecure
where it is show commented out (from suggestion for Mongoose), but it doesn't make a difference. What can be the cause and how can I fix this?
PS I've also tried various things like
const getStorage = async (): Promise<Db> => {
return (await MongoClient.connect(config.mongo.connectionUri, {
tls: true,
//sslCA: fs.readFileSync('./YandexInternalRootCA.crt'),
tlsCertificateFile: './YandexInternalRootCA.crt',
tlsInsecure: true,
})).db()
}
which still gives the same result.
Solution 1:[1]
If you use mongodb
npm package version 4 or higher, you should pass TLS options like this:
const options = {
tls: true,
tlsCAFile: './YandexInternalRootCA.crt'
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nikolay Matrosov |