Mongoose warns: DeprecationWarning: current Server Discovery and Monitoring engine is deprecated? - node.js

When starting up my application, I get the following warning:
(node:11800) DeprecationWarning: current Server Discovery and
Monitoring engine is deprecated, and will be removed in a future
version. To use the new Server Discover and Monitoring engine, pass
option { useUnifiedTopology: true } to the MongoClient constructor.
Yet we are specifying this value:
connection = await mongoose.connect(dbUrl, {
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
The value for dbUrl is: mongodb://localhost:27017/test-app
Environment:
mongo v4.0.13 on macOS
nodejs v10.15.3
package mongodb#3.3.2
package mongoose#5.7.0
Any ideas on how to deal with the warning?

This happens due to change in public ip address
The only way that worked for me is by changing my public ip address inside mongodb atlas
Go to cluster>network access>click on edit
then change the ip address with your current public ip address
for checking you ip address type what is my public ip address on google and follow the first link

This works fine for me, and no more errors.
try this,
mongoose
.connect(db,{
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));

Related

Mongoose opening too many Mongodb connections

I am new to mongoose/mongodb and would like some help on making database connections. I am observing that my express/next app is opening too many connections causing an alert on my Atlas hosted MongoDB.
I am making connections using mongoose(version 5.12.3) in a pretty standard way. Haven't defined any pool size (understand mongoose standard is 5) or timeout related issues. The connection is made twice - once for the application queries and second as a part of Mongo session store. I am just running 5 such node servers.
What I observed is - after reaching threshold, I killed each node server, one at a time. Still my atlas was showing some 23 connections. So I completely removed the network access to my node server and yet it took a while to come to zero. Then I started 2 of my node processes and I suddenly saw number of connections jumping to 60. As I do more and more activities on my node server, I just see this count ever increasing. And sometimes, without good reason, it shows a sudden dip. Also it's not that I have time consuming queries. Although I haven't measured time, generally the client side result is shown within a flash of a second. I am also not closing the connection on SIGTERM/SIGKILL.
I have following specific questions:
What are the recommended connection parameters for production usage?
Should I be closing connection on SIGTERM/SIGKILL?
What is the reason, for my 5 node processes, Atlas now shows about 70+ connections? The number varies with time - possibly correlated to user actions.
Is it that the number just kept on adding upon each bounce/restart of my node server and hence one fine day it reached threshold?
Below is code I use:
To create mongoose connection for queries:
mongoose.connect(process.env.INRMONGODB,
{useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true},
(err) => {
if (err) {
console.log(err, "MONGODB CONNECTION ERROR");
return false;
}
console.log("Mongoose Is Connected");
}
);
As a part of sessionStore:
app.use(session({
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
rolling: false,
name: process.env.COOKIENAME,
cookie: sessionCookieOptions,
store: new MongoStore({
uri: process.env.INRMONGODB, ttl: 2000, autoRemove: 'interval', autoRemoveInterval: 20, // In minutes
hash: {
salt: process.env.SALTSECRET,
algorithm: 'sha1'
}
})
}));
I also tried adding mongoose connection event handlers to see if anywhere any disconnection is happening - but that is not the case. Please guide.
Well, I would use the existing connection for the MongoStore.
mongoose.connect(process.env.MONGO_CONNECTION_URL, { useNewUrlParser: true, useCreateIndex:true, useUnifiedTopology: true, useFindAndModify : true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log('Database connected...');
}).catch(err => {
console.log('Connection failed...')
});
// Session store
let mongoStore = new MongoDbStore({
mongooseConnection: connection,
collection: 'sessions'
})
You might have look at my project where, I have used these things.
Project source code

Deprecation warning when connecting to mongoose

I'm connecting to a mongoose db, and I get a deprecation warning every time I try to connect.
(node:14933) DeprecationWarning: current Server Discovery and
Monitoring engine is deprecated, and will be removed in a future
version. To use the new Server Discover and Monitoring engine, pass
option { useUnifiedTopology: true } to the MongoClient constructor.
I set useUnifiedTopology to true but I'm still getting the error. What am I doing wrong and how can I fix it?
const mongooseOptions = {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
};
const dbUrl = config.get('dbUrl');
await mongoose.connect(dbUrl, mongooseOptions);
The DeprecationWarning for useUnifiedTopology comes from the underlying mongodb driver. Any connections will need this setting to use the new connection management.
In agenda, pass in options:
const agenda = new Agenda({
db: {
address: 'mongodb://localhost:27017/agenda',
options: {
useUnifiedTopology: true,
useNewUrlParser: true,
}
}
})
It looks like agenda can also reuse an existing mongoose connection by passing in the underlying mongodb db, something like:
const agenda = new Agenda({
mongo: mongoose.connection.db('agenda-test')
})

Mongodb useUnifiedTopology automatically create a new connection [duplicate]

I am having a kind of strange problem when I trying to establish a single mongodb connection to a db with the mongodb nodejs native driver in the version 3.6.0.
My idea is to have just one connection opened through all the client session and reuse it in the different routes I have in my express server, when I hit it the first time the getDatabase function it creates two connections and after that one of it closes and one stands idle, but when I use a route, the second get opened again (it is like one connection just stays there and do nothing).
I just want to have one connection opened in my pool.
If you see the commented code i was testing with those options but none of them worked for me.
Pd: when I set the socketTimeoutMS to 5000ms just one connection is created but it auto-closes and reopen each 5000ms, which is weird (it reopen itself even when I don't use the connection).
All of this problem happen when I set the useUnifiedTopology to true (I can't set it to false because is deprecated and the other topologies will be removed in the next version of mdb ndjs driver)
Here is an image with the strange behaviour
The code is:
import { MongoClient, Db } from 'mongodb';
import { DB_URI } from '../config/config';
// This mod works as DataBase Singleton
let db: Db;
export const getDataBase = async (id: string) => {
try {
if (db) {
console.log('ALREADY CREATED');
return db;
} else {
console.log('CREATING');
let client: MongoClient = await MongoClient.connect(`${DB_URI}DB_${id}`, {
useUnifiedTopology: true,
/* minPoolSize: 1,
maxPoolSize: 1,
socketTimeoutMS: 180000,
keepAlive: true,
maxIdleTimeMS:10000
useNewUrlParser: true,
keepAlive: true,
w: 'majority',
wtimeout: 5000,
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 8000,
appname: 'myApp',
*/
});
db = client.db();
return db;
}
} catch (error) {
console.log('DB Connection error', error);
}
};
The driver internally creates one connection per known server for monitoring purposes. This connection is not used for application operations.
Hence, it is expected that you would get two connections established.

How to create installation script for app build on node.js, which include installation of dump of data base (mongo) , installation of camunda server?

I am trying to build an installation script for an app which made on node.js. As of now, I have to manually install the database dump, run Mongo server, npm packages and run Camunda server. So, is there any way I can do all those things by running a single script.
Please bear with my silly question.
Thanks in advance
you can call mongodump command from nodejs as discussed here
about mongo server, you can start it in your app:
import { connect } from 'mongoose'; // MongoDB ORM
connect(conf.db[conf.env], {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
.then(() => console.log(`connected to ${conf.db[conf.env]}`))
I need to say above code is written in ES6, if you don't use it you need to set Babel or use older code style:
const mongoose = require('mongoose');
mongoose.connect('url/of/your/db', {
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
}, function (error) {
if (error) { // do sth with error
}
console.log('connected successfully');
}
I hope it helps you with your problem

Cosmos DB with Mongoose - Initial connection closes but is fine after auto re-connect

I have a weird thing going on here: I'm connecting to Azure's Cosmos DB using Mongoose 5.9.7 with the following code:
const mongoose = require('mongoose');
(async () => {
mongoose.connection.on('disconnected', () => {
console.log(new Date().toJSON(), 'disconnected!')
})
mongoose.connection.on('error', e => {
console.log(new Date().toJSON(), 'error', e);
})
mongoose.connection.on('connected', () => {
console.log(new Date().toJSON(), 'connected!')
})
await mongoose.connect(
'mongodb://<DB_HOST>:<DP_PORT>',
{
dbName: <DB_NAME>,
auth: {
user: <DB_USER>,
password: <DB_PASS>,
},
ssl: true,
useNewUrlParser: true,
useFindAndModify: true,
useCreateIndex: true,
useUnifiedTopology: true,
}
)
})();
Now after pretty much exactly 10 seconds the client is disconnected. After another 10 seconds the auto re-connect kicks in, connects and then the connection stays stable. If I set useUnifiedTopology to false the initial connection stays alive without the disconnect after 10 secs.
Any idea what might be causing this behavior?
I tried to connect to my cosmos db by using the code you provided,then it worked and the connection stayed stable whatever I set useUnifiedTopology true or false.By the way,my node.js version is v12.16.2 and the version of mongoose is 5.9.12.
Set useUnifiedTopology:true:
Set useUnifiedTopology:false:
The false option of useUnifiedTopology will be removed in a future version and it maybe update the newer data with an older value,so set useUnifiedTopology:false is not a Long-term solutions.
UnifiedTopology:ture use a server selection loop and retry the operation one time in the event of a retryable error.More details please refer to this article.

Resources