Reputation: 375
How to connect mongodb with digital ocean database using mongoose. I tried this way it does not work. Although in local it says Error: ENAMETOOLONG: name too long, open to the CA_CERT. Please guide
mongoose
.connect(process.env.HOST, {
useNewUrlParser: true,
useCreateIndex: true,
ssl: true,
sslCA: process.env.CA_CERT.replace(/\\n/g, '\n')
})
Upvotes: 3
Views: 1671
Reputation: 650
you must have an CA-certificate in local storage. this code used with express and babel:
import fs from 'fs'; import mongoose from 'mongoose';
let mongoCertPath = "./SSL/ca-certificate.crt";
if (fs.existsSync(mongoCertPath)) {
mongoose.Promise=global.Promise;
mongoose.connect(process.env.MONGO_URI,{
useNewUrlParser: true,
useUnifiedTopology: true,
ssl: true,
tlsCAFile: mongoCertPath
}).then(
()=>{ console.log('conectado a digitalOcean mongoDB: db_default'); },
err=>{console.log('error conectando digitalOcean mongoDB:'+err);}
);
}else{
console.log('no existe el -> SSL ca-certificate.crt')
}
Upvotes: 0
Reputation: 797
Below approach worked for me
const mongoose = require("mongoose");
const colors = require("colors");
const path = require("path");
module.exports = async (server) => {
try {
let mongoCertPath = path.resolve("./config/ca-certificate.crt");
if (process.env.CA_CERT) {
fs.writeFileSync(mongoCertPath, process.env.CA_CERT);
}
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
tlsCAFile: mongoCertPath
});
console.log("mongo connection successful..".yellow);
server.listen(process.env.PORT || 5000, () =>
console.log(
`server running on ${process.env.NODE_ENV} mode, port ${process.env.PORT}..`
.yellow
)
);
} catch (error) {
console.log("mongo connection failed..".red);
console.log(error);
process.exit(1);
}
};
my .env look like this
MONGO_URI = mongodb+srv://doadmin:[email protected]/admin?authSource=admin&replicaSet=db-mongodb-blr1-xxxxx&tls=true
Upvotes: 1
Reputation: 48
As I understand mongoose doesn’t have any property to set TLS CRT content (CA_CERT env variable from DigitalOcean), I decided to create a CRT file on the fly and then use it to connect to DB, then delete the created file.
const filenameToCreate = 'test.crt';
fs.writeFileSync(filenameToCreate, process.env.CA_CERT);
mongoose.connect(dbConnectionUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
tlsCAFile: filenameToCreate
}).then((ers) => {
app.listen(port, () => console.log(`server is listening on ${port}`));
}).catch(err => {
console.log(err);
}).finally(() => {
fs.unlinkSync(filenameToCreate);
})
I am not sure that this is an acceptable approach.
Upvotes: 0