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.
Related
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.
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've tried to follow this tutorial https://www.youtube.com/watch?v=VF38U2qd27Q, but to no avail.
I realised that the syntax in the video already obsolete for example connectWithUri to become connect.
but when I tried to connect to mongo using deno_mongo with the latest docs, it still not working.
import { MongoClient } from "https://deno.land/x/mongo#v0.20.1/mod.ts";
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
const client = new MongoClient();
client.connect(dbString);
const db = client.database(mongoDB)
this.users = db.collection<UserSchema>("users");
Then I found another library denodb but again can't connect to mongodb:
import { Database } from 'https://deno.land/x/denodb/mod.ts';
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
this.db = new Database('mongo', {
uri: dbString,
database: mongoDB
});
the error message:
error: Uncaught AssertionError
deno | throw new AssertionError(msg);
deno | ^
deno | at assert (asserts.ts:152:11)
deno | at MongoClient.database (client.ts:48:5)
deno | at new connectDB (connectDB.ts:35:23)
which part is wrong?
Looking at the deno_mongo README on GitHub.
For a local database you should use
//Connecting to a Local Database
await client.connect("mongodb://localhost:27017");
And if you are connecting to Mongo Atlas Database (and probably any other remote database) you should use:
//Connecting to a Mongo Atlas Database
await client.connect({
db: "<db_name>",
tls: true,
servers: [
{
host: "<db_cluster_url>",
port: 27017,
},
],
credential: {
username: "<username>",
password: "<password>",
db: "<db_name>",
mechanism: "SCRAM-SHA-1",
},
});
FYI
If you are using Mongo Atlas make sure to split up the connection string you get from 'Connection Wizard' in the Mongo Atlas dashboard over 3 (or how many replicas you have) entries in the server array. Like this:
servers: [
{
host: this.dbUrl1, // e.g. <name-of-cluster>-00-00.fbnrc.mongodb.net
port: 27017,
},
{
host: this.dbUrl2, // e.g. <name-of-cluster>-00-01.fbnrc.mongodb.net
port: 27017,
},
{
host: this.dbUrl3, // e.g. <name-of-cluster>-00-02.fbnrc.mongodb.net
port: 27017,
}
]
You get the connection string by:
Click 'Clusters' under Data storage (left side of the screen)
Click 'Connect' button
Click 'Connect to Application'
Select Driver: 'Node.js' and Version: '2.2.12 or later'
Connection string is displayed below. The servers are listed in a comma separated manner like this:
...<name-of-cluster>-00-00.fbnrc.mongodb.net:27017,<name-of-cluster>-00-01.fbnrc.mongodb.net:27017,<name-of-cluster>-00-02.fbnrc.mongodb.net:27017...
FYI-2
Make sure the master replica is listed first in the server array. Because if you want to do insertions into the database the master replica should be targeted. For me this was the 2nd mongo url, therefore the following server array worked for me:
servers: [
{
host: this.dbUrl2,
port: 27017,
},
{
host: this.dbUrl1,
port: 27017,
},
{
host: this.dbUrl3,
port: 27017,
}
]
the below code is working for me.
import { DataTypes, Database, Model } from 'https://deno.land/x/denodb/mod.ts';
const db = new Database('mongo', {
host: 'mongodb://localhost:27017',
username: '',
password: '',
database: 'DBMYAPP',
});
console.log(db)
I also faced the same issue while updating deno_mongo to the latest version. Use await to resolve client.connect method
Try this:
import { MongoClient } from "https://deno.land/x/mongo#v0.20.1/mod.ts";
const dbString = `mongodb://${mongoUser}:${mongoPass}#${mongoHost}:${mongoPort}`;
const client = new MongoClient();
await client.connect(dbString);
const db = client.database(mongoDB)
this.users = db.collection<UserSchema>("users");
I had the same problem on windows 10, so try this
on your local mongodb:
await client.connect("mongodb://127.0.0.1:27017");
I upgrade sails to 1.0, I resolved all the other errors but not able to resolved database connection issue,
It will be really helpful if anyone can reply on this.
module.exports.datastores = {
localDiskDb: {
adapter: 'sails-disk'
},
postgreSql: {
adapter: 'sails-postgresql',
// url: 'postgresql://admin:root#localhost:5432/testdb',
// ssl: true,
host: 'localhost',
user: 'admin',
password: 'root',
database: 'testdb'
},
};
Important Error Logs
I was using password which contains %
after changing the password sails successfully connected to postgresql.
It mostly looks like bug with Sails v1 or Sails-pgsql adapter.