How to connect to ComosDB(Mongo API) with options?
"options": {
"ssl": true,
"server": {
"socketOptions": {
"keepAlive": 300000,
"connectTimeoutMS": 30000
}
},
"replset": {
"socketOptions": {
"keepAlive": 300000,
"connectTimeoutMS": 30000
}
}
}
I tried to connect with mongoose.connect(uri,options) but I received 500 error.
err: { MongoError: connection 0 to xName.documents.azure.com:port timed out
at Function.MongoError.create (/home/mic3ael/src/prizmacloud/node_modules/mongodb-core/lib/error.js:29:11)
at Socket.<anonymous> (/home/mic3ael/src/prizmacloud/node_modules/mongodb-core/lib/connection/connection.js:188:20)
at Object.onceWrapper (events.js:314:30)
at emitNone (events.js:105:13)
at Socket.emit (events.js:207:7)
at Socket._onTimeout (net.js:401:8)
at ontimeout (timers.js:488:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:283:5)
name: 'MongoError',
message: 'connection 0 to xName.documents.azure.com:port timed out' }
when I added to uri string ?ssl=true as a string without options param, it worked well otherwise when I passed {ssl=true} as an object as options param, it didn't work.
mongoose version is "mongoose": "~4.9.1"
The question is how to add options an object as options param for azure CosmosDB or as a string.
Thanks, Michael.
I have just found the solution:
const qs = require('qs');
mongoose.connect(`mongodb://${config.username}:${config.password}#${config.host}:${config.port}/${config.database}?${qs.stringify(config.options)}`)
It connects uri with options string.
Michael.
Please try to move "ssl": true, to server object.
"options": {
"server": {
"ssl": true,
"socketOptions": {
"keepAlive": 300000,
"connectTimeoutMS": 30000
}
},
"replset": {
"socketOptions": {
"keepAlive": 300000,
"connectTimeoutMS": 30000
}
}
}
Related
I am trying to connect a NodeJS server to an AWS documentDB cluster with TLS enabled. The NodeJS server is hosted on an EC2 instance and it's on the same VPC as the documentDB cluster. But I'm getting the following error:
{ MongoServerSelectionError: unable to get local issuer certificate
at Timeout.waitQueueMember.timer.setTimeout [as _onTimeout] (/home/ubuntu/server/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
name: 'MongoServerSelectionError',
reason:
TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers:
Map {
'*******.cluster-****.us-east-1.docdb.amazonaws.com:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null } }
The error seems to be with the TLS certificate. But I'm passing the contents of rds-combined-ca-bundle.pem while connecting as shown in the following code:
uri = process.env.MONGODB_URI || process.env.Db_url;
options = {
user: "****",
pass: "****",
}
mongoose.set("useCreateIndex", true);
mongoose.connect(
uri,
{
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
sslCA: [fs.readFileSync("/home/ubuntu/rds-combined-ca-bundle.pem")],
},
err => {
if (err) {
console.log('Connection Error: ', err);
} else {
console.log(`Successfully Connected============`);
}
}
);
I've tried connecting to the mongo cluster using mongo shell on EC2 instance using
mongo --ssl --host *******.cluster-****.us-east-1.docdb.amazonaws.com:27017 \
--sslCAFile rds-combined-ca-bundle.pem --username ***** --password *****
and this is working. So, the connection to the cluster is fine, but the mongoose cannot connect.
Is there any other way to connect to documentDB using mongoose?
Can you add ssl: true ? Something like this works for me:
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://user:password#docdb_uri',
{
useNewUrlParser: true,
ssl: true,
sslValidate: true,
sslCA: `/usr/local/rds-combined-ca-bundle.pem`
})
}
I downloaded MongoDB with Compass and the shell as accessories and started learning from W3Schools Node.js MongoDB section.
Step 1: type into command prompt>npm install mongodb
success
step 2: create a MongoClient object file with this code and then save
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Step 3: Once the code above is saved run the file by calling it on the command prompt
C:\Users\MyName>node fileName.js
and this is the response I'm getting
C:\Users\*****\MongoDB Tutorials>node demo_create_mongo_db.js
C:\Users\*****\node_modules\mongodb\lib\utils.js:418
throw error;
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\*****\node_modules\mongodb\lib\sdam\topology.js:293:38)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 11442648,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\*****\node_modules\mongodb\lib\cmap\connect.js:379:20)
at Socket.<anonymous> (C:\Users\*****\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:510:26)
at Socket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v17.2.0
What do I do about this?
The code:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
let dataBase;
async function connect() {
const client = await MongoClient.connect('mongodb://localhost:27017');
dataBase = client.db('blog');
};
function getDb() {
if (!dataBase) {
throw { message: "Database connection not established" };
}
return dataBase;
};
module.exports = {
connectToDatabase: connect,
getDb: getDb
};
I keep getting this message:
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
...
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:305:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 85766126,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
at Socket.<anonymous> (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
try to change the mongodb://localhost:27017 to mongodb://127.0.0.1:27017 sometimes the localhost is not recognized.
I hope it was helpful
Please see below the error that I am getting while executing a lambda after
a particular time interval. Any suggestions will be appreciated.
"pid": 1,
"level": 50,
"err": {
"message": "Connection terminated unexpectedly",
"name": "SequelizeConnectionError",
"stack": "SequelizeConnectionError: Connection terminated unexpectedly\n
at connection.connect.err
(/var/task/node_modules/sequelize/lib/dialects/postgres/connection-
manager.js:132:20)\n at Connection.con.once
(/var/task/node_modules/pg/lib/client.js:211:11)\n at Object.onceWrapper
(events.js:313:30)\n at emitNone (events.js:106:13)\n at
Connection.emit (events.js:208:7)\n at Socket.
(/var/task/node_modules/pg/lib/connection.js:130:10)\n at emitNone
(events.js:111:20)\n at Socket.emit (events.js:208:7)\n at
endReadableNT (_stream_readable.js:1064:12)\n at _combinedTickCallback
(internal/process/next_tick.js:138:11)\n at process._tickDomainCallback
(internal/process/next_tick.js:218:9)"
},
"msg": "Connection terminated unexpectedly"
The DB connection code is as below
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER,
process.env.DB_PWD, {
host: process.env.DB_HOST,
dialect: 'postgres',
logging: process.env.DB_SHOW_LOGS === 'true',
port: process.env.DB_PORT,
pool: {
max: 5,
min: 1,
acquire: 30000,
idle: 10000
},
operatorsAliases: false
});
I'm trying to connect to a postgre(heroku) with the sequelize.
But the sequelize returns an error when starting my application
Help me us.
Error message returned when you run the command "node app.js":
$ node app.js
assert.js:42
throw new errors.AssertionError({
^
AssertionError [ERR_ASSERTION]: false == true
at Object.exports.connect (_tls_wrap.js:1036:3)
at Socket.<anonymous> (C:\DaniloNote\Pessoal\Projetos-Testes\Node8AndSequelize\node_modules\pg\lib\connection.js:94:23)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:607:20)
My file package.json
{
"name": "teste",
"description": "teste",
"author": "danilo <danilovex#gmail.com>",
"version": "0.1.0",
"engines": {
"node": "8.11.1"
},
"dependencies": {
"pg": "^7.4.2",
"pg-hstore": "^2.3.2",
"sequelize": "^4.37.7"
}
}
My file app.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'host',
dialect: 'postgres',
dialectOptions: {
ssl: true
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
This error happened when I updated my package to version 8 of the node.
Tks.