I'm stuck in connecting my Nestjs server to the MongoDB database both are on the same app platform in the digital ocean. The main problem is in providing the ca.certificate.crt file to the Nestjs server. I'm using MongoDB with typeorm and nestjs.
const mongodb_config: ConnectionOptions = {
type: "mongodb",
url: `${getValue("MONGO_URL")}/${MONGODB_DATABASE}`,
name: DB_CONNECTION.MONGO_CONNECTION,
entities: [LivePriceEntity],
logging: ENVIRONMENT === ENVIRONMENTS.LOCAL,
useUnifiedTopology: true,
useNewUrlParser: true,
ssl: ENVIRONMENT === ENVIRONMENTS.LOCAL ? false : true,
sslValidate: ENVIRONMENT === ENVIRONMENTS.LOCAL ? false : true,
sslCert: ENVIRONMENT === ENVIRONMENTS.LOCAL ? "" : SSL_CA_CERT,
cli: {
entitiesDir: "src/app/**/entities/*.entity{.ts,.js}",
}
};
This is my typeorm connection config. Please help me out.
Related
I have been working on an small app and connecting with Heroku PostgreSQL, for many days was working right but now is showing me this SSL error
The server does not support SSL connections
I have been looking for solutions but I cannot find anything that works for me, my code is:
import pg from 'pg'
import db from '../config.js'
const pool = new pg.Pool({
host: db.host,
database: db.database,
user: db.user,
port: db.port,
password: db.password,
ssl: { rejectUnauthorized: false },
})
export default function query(text, params) {
return pool.query(text, params)
}
Try changing it from Pool to Client and then using that to connect and query.
async function get(){
const client = new pg.Client({
ssl: {
rejectUnauthorized: false
},
user: ...,
password: ...,
port: ...,
host: ...,
database: ...
});
client.connect();
const response = await client.query(`SELECT * FROM ...;`)
return response.rows
}
Double check your values in the Heroku database.
Also, in production, you should just need
const client = new pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
},
}
The first set of code is for local connection to your db.
One last note, I would put your user, password, etc... into a .env file and don't commit that to your repo.
UPDATE:
You can also put this into a config file like ./db.config.js as the following
const pg = require('pg')
module.exports =
process.env.DATABASE_URL
?
new pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
},
})
:
new pg.Client({
// connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
},
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
port: process.env.DATABASE_PORT,
host: process.env.DATABASE_HOST,
database: process.env.DATABASE
})
So if it is in production, it will use the database url, and if there is none (which is local) then it will use the username password connection.
I’m trying to connect to RDS and seed data.
ormconfig.js
const entities = process.env.NODE_ENV === 'test' ? ['./src/**/**/*.ts'] : ['./dist/**/**/*.js'];
const logging = process.env.NODE_ENV !== 'test';
module.exports = {
type: 'postgres',
host: 'rds.ap-northeast-1.rds.amazonaws.com',
port: 5432,
username: 'postgres',
password: 'password',
database: 'db',
synchronize: true,
migrationsRun: false,
logging,
migrations: [`${__dirname}/dist/migration/*.js`],
entities,
};
// # sourceMappingURL=ormconfig.js.map
Error
✖ Database connection failed! Check your typeORM config file.
RDS is running for sure and all the values of DB are from AWS Secrets Manager, so they are correct.
Why is this happening?
I'm trying to migrate my mongo database from Compose to IBM Cloud Databases for Mongo and in their documnetations (https://www.compose.com/articles/exporting-databases-from-compose-for-mongodb-to-ibm-cloud/): "With a new Databases for MongoDB deployment, you'll be provided with a replica set of two endpoints to connect to your database. Databases for MongoDB also uses a TLS certificate, so you'll need to configure your MongoDB application driver to accept two hosts and a TLS certificate"
How can I set the TLS certificate provided by IBM Cloud in Mongoose connection ?
Nothing I've tried worked :(
I can see my database if I'm using the IBM cli but from my node.js application I cannot connect to it
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
absolute nothing is working even the database is there
Please help me
I'm also facing same problem
this works for me
mongoose.connect(‘mongodb+srv://username:password#host/db_name?authSource=admin&replicaSet=repliasetname&tls=true&tlsCAFile=/root/ca-certificate.crt’,{some config})
Try the following:
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)```
I did it locally, you need to install the tunnel first
$ ssh -i "IF YOU HAVE PEM.pem" -L <27017:YOUR_AMAZON_HOST:27017> <server_user_name#server_ip_OR_server_url> -N
I managed to implement it as follows
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');
};
You need to set
MONGODB_USER
MONGODB_PASSWORD
does anyone know how to connect to Google Cloud SQL from Sequelize?
sequelize = new Sequelize(process.env.TEST_DB || 'postgres', 'blah', null, {
dialect: 'postgres',
operatorsAliases: Sequelize.Op,
host: process.env.DB_HOST || 'localhost',
define: {
underscored: true
},
});
connected = true;
index.js
const sequelize = new Sequelize('{db_name}', '{db_user}', '{db_password}', {
dialect: 'mysql',
host: '/cloudsql/{instance}',
timestamps: false,
dialectOptions: {
socketPath: '/cloudsql/{instance}'
},
});
add this in serverless.yml
beta_settings:
cloud_sql_instances: {xxxxxxx-xxxxxx:us-central1:xxxxxxxxxxx}
You can connect from Sequelize like from any other client tool or ORM. Getting the access correctly depends on where you are running your code. If you code runs outside GCP, you can follow the external app instructions on this page:
https://cloud.google.com/sql/docs/postgres/connect-external-app.
If you are using proxy in your local computer, you set process.env.DB_HOST to 127.0.0.1. You can find troubleshooting tips at https://cloud.google.com/sql/docs/postgres/sql-proxy#troubleshooting.
My connection to my mongo database will close or timeout if left in active. I'm getting the following error when I leave my app in active "no open connections"
My mongo DB is running in a replication set up on AWS. I'm using the following options when connecting using mongoose. I'm unsure if any other flags should be set. I was basing my options on teh monodo node driver doc # http://mongodb.github.io/node-mongodb-native/api-generated/server.html.Users will be in my applicaiton for 8+ hours at a time and I don't want anything to timout when they go to lunch or leave for a meeting.
MongoOptions : {
user: 'root',
pass: '********',
replset: {
auto_reconnect: true,
poolSize: 25,
socketOptions: { keepAlive: 1 },
ssl: true,
sslCert: fs.readFileSync('./server/config/ssl/mongodb-cert.crt'),
sslKey: fs.readFileSync('./server/config/ssl/mongodb-cert.key')}
}
mongoose.connect('mongodb://server.com:27017', config.MongoOptions);
The connection getting closed turned out to be another issue that was causing the problem.
We have a replicate set running w/ SSL and are able to keep the connection up for days using the following config:
MongoOptions : {
user: 'ssssss',
pass: 'xxxxxx',
replset: {
auto_reconnect: false,
poolSize: 10,
socketOptions: { keepAlive: 1 },
ssl: true,
sslCert: fs.readFileSync('./server/config/ssl/mongodb-cert.crt'),
sslKey: fs.readFileSync('./server/config/ssl/mongodb-cert.key')}
}
Try adding
connectTimeout: 43200000
that should be good for 12 hours