简体   繁体   中英

mongoose connect with CA_CERT using SSL digital ocean

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')
  })

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:xxxxxx@db-mongodb-blrxx1-xxxxx-xxxxx.mongo.ondigitalocean.com/admin?authSource=admin&replicaSet=db-mongodb-blr1-xxxxx&tls=true

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.

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')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM