How to add useUnifiedtopology property to MongoClient constructor - node.js

(node:8041) 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.

With connect function:
mongoose.connect('mongodb://localhost:27017/DATABASE', { useUnifiedTopology: true }});
With MongoClient:
var mongoclient = new MongoClient(new Server("localhost", 27017), { useUnifiedTopology: true });
Simply send options object to second parameter.

Related

How to find the Mongodb credentials from the config file?

I've recently joined to a project that uses Mongodb. I'm a newbie to this database. I need to find the database credentials to get an export of it (as a backup) before everything.
The doc says, the connect() method would have these parameters:
connect(url, user, password)
But I don't see that syntax in the real project. Here is the content of mongoose.js file:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(
'mongodb://bpAdmin:Bp1400##32.150.189.207:27017/bpDB?authSource=admin',
{
useCreateIndex: true,
useFindAndModify: true,
useNewUrlParser: true,
useUnifiedTopology: true,
autoIndex: true,
}
);
mongoose.set('useCreateIndex', true);
module.exports = {
mongoose,
};
(The IP and some other names just changed because of some security reasons)
Could you please tell me what's the user and password and db name?
Check out the format in offical documentation on connection string,
mongodb://[username:password#]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
So for your questions,
info
value
username
bpAdmin
password
Bp1400#
db name used for auth
admin
default db to connect to
bpDB

MongoDB can be connected with MongoClient but not mongoose

So when I run my app in deployment, with the backend connecting to MongoDB using MongoClient as follow:
import { MongoClient } from 'mongodb'
const url = process.env.MONGODB_URI
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },(err, db)=>{
console.log(url)
db.close()
})
everything works fine. But if I change it into
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
it gives the following error:
webpack://HappyHourWeb/./server/server.js?:29
throw new Error(`unable to connect to database: ${_config_config__WEBPACK_IMPORTED_MODULE_0__["default"].mongoUri}`)
^
Error: unable to connect to database: my_database_url,
at NativeConnection.eval (webpack://HappyHourWeb/./server/server.js?:29:9)
at NativeConnection.emit (node:events:390:28)
at /Users/Hieudo/Documents/Project/HappyHourWeb/node_modules/mongoose/lib/connection.js:807:30
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Any help is greatly appreciated!
According to various sources, including MongoDB Connection String URI reference, Mongoose connection docs (Ctrl+F and search for srv to jump to the right topic) and the most upvoted answer on this question on SO, you should handle standard URIs and DNS URIs differently.
Mongoose accepts a dbName option that is
[...]useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.
The fact that the native MongoDB driver handles it automatically doesn't necessarily means that Mongoose will. Try separating the DB name from the URI and pass it as the second argument when connecting with Mongoose.
Also, that part of your code :
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
doesn't check for connection errors, it emits an event if an error is encountered after the initial connection has been made.
As Joe pointed out in the comments, you should handle both the initial connection errors AND errors that may come after it, either with the try/catch syntax or the .catch callback. More info in the docs.

{useNewUrlParser: true, useUnifiedTopology: true} what is the use of this in mongoose [duplicate]

This question already has answers here:
What does useNewURLParser and userCreateIndex in mongoose.connect() do?
(1 answer)
Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true
(22 answers)
Server Discovery And Monitoring engine is deprecated
(30 answers)
Closed 1 year ago.
After Installing mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
What is the use of useNewUrlParser and useUnifiedToplogy ?
According to the documentation:
-->unifiedtopology : 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.
-->usenewurlparser :
DeprecationWarning: current URL string parser is deprecated, and will be
removed in a future version. To use the new parser, pass option
{ useNewUrlParser: true } to MongoClient.connect.

Mongoose 4.11.0 Promises timing out

I'm using mongoose and bluebird.
The setup is by-the-book, and is using the useMongoClient option, as requested by the notification.
Mongoose.connect(myConnectionString, {useMongoClient: true});
however none of the promises I use execute.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/starbucks', { useMongoClient:
true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('openUri', function() {
// we're connected!
});
I have used this code for latest version and warning has gone. Please try it. Or use older version.
I've found that this is likely a bug with mongoose
problem went away after rolling back mongoose version
npm uninstall -save mongoose
npm install -save mongoose#4.10.8
OR you can remove the useMongoClient option Mongoose.connect(connectionString);, and ignore the message
DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection()
https://github.com/Automattic/mongoose/blob/master/History.md
shows
hope this helps someone
This code solves all deprecation warnings:
mongoose.Promise = global.Promise;
mongoose.connect(uri, {
keepAlive: true,
reconnectTries: Number.MAX_VALUE,
useMongoClient: true
});
Example:
const mongoose = require("mongoose");
module.exports.connect = uri => {
mongoose.connect(uri, {
keepAlive: true,
reconnectTries: Number.MAX_VALUE,
useMongoClient: true
});
// plug in the promise library:
mongoose.Promise = global.Promise;
mongoose.connection.on("error", err => {
console.error(`Mongoose connection error: ${err}`);
process.exit(1);
});
// load models
require("./user");
};
For further reading, a contributor discusses new behaviors here: https://github.com/Automattic/mongoose/issues/5399#issuecomment-312523545

How to use node-mongodb-connection for connect-mongo

I make connection to my database like the following:
var mongoClient = new MongoClient(new Server('localhost', 27017, {auto_reconnect: true}));
mongoClient.open(function (err, mongoClient) {
var db = mongoClient.db('db_name');
db.authenticate('user', 'password', function () {err, result} {
if (err || !result) return console.log('error');
app.use(express.session({
store: new MongoStore({
db: db
})
});
});
});
And I want to share db connection with MongoStore but it's seem not work. How should I do that?
EDIT: I'm using authentication on my database but after new MongoStore() get executes I'm getting the following error:
not authorized for query on site.system.indexes
This is how it works for me,
var connectionString = "mongodb://username:password#localhost:27017/db_name";
var dbOptions = {
server:{
'auto_reconnect': true,
'poolSize': 20,
socketOptions: {keepAlive: 1}
}
}
// For long running applictions it is often prudent to enable keepAlive. Without it,
// after some period of time you may start to see "connection closed" errors for what
// seems like no reason.
MongoClient.connect(connectionString, dbOptions, function(err, db) {
if(err){
console.log(err);
}
app.use(express.session({
store:new mongoStore({db: db}),
secret: 'secret'
}));
})
This works perfectly for me and it will not give you not authorized issues as well. Previously we don't need to give keepAlive option and it works perfectly witout it but with a release of mongodb 2.4 for long running applications we need to give keepAlive option otherwise we keep getting connection closed or not authorized sort of errors.

Resources