Mongoose 4.11.0 Promises timing out - node.js

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

Related

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.

How to add useUnifiedtopology property to MongoClient constructor

(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.

Problem connecting to MongoDB Atlas cluster with mongoose (NodeJS)

I've been struggling to connect to my mongodb atlas cluster through mongoose. I'm still fairly new to nodejs, but after searching around all I could find was to set the flag to
useNewUrlParser: true and my own compiler threw a warning for me to add useUnifiedTopology: true. However it keeps getting caught as an error. Thanks for any advice or direction
Update: when outputting err, i get
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
going to dig into this now
//THIS IS PART OF .ENV
ATLAS_URI=mongodb+srv://myusername:mypw#cluster(:idhere).mongodb.net/test?retryWrites=true&w=majority
//THIS IS PART OF SERVER.JS
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const uri = process.env.ATLAS_URI;
// console.log('URI = "' + uri + '"'); //outputs correct URI
//without these two flags, get deprecated warning
mongoose.connect( uri, { useNewUrlParser: true, useUnifiedTopology: true })
.catch(err => {
console.log('URI error'); //still goes into here
});

Error connecting to Azure: Illegal character in password with mongoose 5.0.1 but works in 4.13.9

I have a node.js application that is deployed to azure using CosmosDB and the MongoDB API. My application uses mongoose which works seamlessly in 4.13.9.
My application that works connects as follows:
var configDB = require('./config/database');
var mongoose = require('mongoose');
mongoose.connect(configDB.url, { useMongoClient: true } );
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
the config/database file is defined as follows (changed username, password, DB to protect the innocent):
module.exports = {
'url': 'mongodb://azureusername:azurepassword#myazuredb.documents.azure.com:10255/?ssl=true'
}
Now the problem comes when I install mongoose 5.0.1. I remove the useMongoClient option from the connect and got rid of the promise so my connect code is now:
mongoose.connect(configDB.url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
When this runs I get the following in the console:
(node:21392) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 2): Error: Password contains an illegal
unescaped character
I can even comment out the connection code to where it is only the mongoose.connect and that is what is giving the error. What am I doing wrong? Is there a breaking change in 5.0.1 that I need to account for? As a side note that may or may not be related, I saw some notes about now giving a callback instead of using promises so if someone has an example of how they do that in a Node/Express app that would be great, but it doesn't seem like that's the isee when I'm getting an error reported on the connect about an illegal character.
NOTE: The config file is exactly the same when running against 4.13.9 or 5.0.1 so I know the password is valid and it is not the issue.
For the latest version (v5.0.1) of Mongoose, you'll need to use this syntax to connect to MongoDB like this:
const mongoose = require('mongoose');
mongoose.connect('mongodb://<cosmosdb-username>.documents.azure.com:10255/<databasename>?ssl=true', {
auth: {
user: '<cosmosdb-username>',
password: '<cosmosdb-password>'
}
})
.then(() => console.log('connection successful'))
.catch((err) => console.error(err));
The password for the Azure Cosmos DB instance I got ended with ==, hence the illegal characters message. These characters must be urlencoded.
An equals sign = urlencoded is %3D.
A properly encoded connection string for the password jitsu== could look like mongodb://user:jitsu%3D%3D#localhost:27017/dbname?ssl=false.
Also be aware that the connection strings you get from the Cosmos DB blade in the Azure Portal doesn't include the database name.
To connect to local cosmos db emulator use the following connection method (for mongoose > 5.0.0):
mongoose.connect(
`mongodb://localhost:10255/?ssl=true`,
{
auth: {
user: "localhost",
password: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
dbName: "admin"
}
}
);
Or you may also do the following:
const encodedPassword = encodeURIComponent("C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
mongoose.connect(`mongodb://localhost:${encodedPassword}#localhost:10255/admin?ssl=true`);
Connection string has following format:
mongodb://username:password#host:port/[database]?ssl=true
and there seems to be some issue with default password character escaping. Thus we encoded it separately.
Add the new url parser as an option { useNewUrlParser: true }
Change you line 3 to:
mongoose.connect(configDB.url, { useMongoClient: true, useNewUrlParser: true } );

mongoose output the error "Error: connection closed"

I stumble upon a curious problem about mongoose connect the mongodb, it generate the detail errors as the following
e:\Mentor_Resources\node\node_twitter_bootstrap>node app
Express server listening on port 3000
Trace: error occure when start to connect dbError: connection closed
at e:\Mentor_Resources\node\node_twitter_bootstrap\server\module\word.js:14:
17
at Connection.open (e:\Mentor_Resources\node\node_twitter_bootstrap\node_mod
ules\mongoose\lib\connection.js:201:5)
at Db.open (e:\Mentor_Resources\node\node_twitter_bootstrap\node_modules\mon
goose\node_modules\mongodb\lib\mongodb\db.js:247:16)
at Server.connect.connectionPool.on.server._serverState (e:\Mentor_Resources
\node\node_twitter_bootstrap\node_modules\mongoose\node_modules\mongodb\lib\mong
odb\connection\server.js:413:7)
at EventEmitter.emit (events.js:115:20)
at connection.on.connectionStatus (e:\Mentor_Resources\node\node_twitter_boo
tstrap\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connect
ion_pool.js:108:15)
at EventEmitter.emit (events.js:91:17)
at Socket.closeHandler (e:\Mentor_Resources\node\node_twitter_bootstrap\node
_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection.js:401:
12)
at Socket.EventEmitter.emit (events.js:88:17)
at Socket._destroy.destroyed (net.js:364:10)
the code snippet of mongoose is:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/word-sentence",function(err) {
if(err)
console.trace('error occure when start to connect db' + err);
});
i am sure the mongodb is open, and i restart mongodb for several times,but the error is still exist, so I reboot my Windows XP , and try again the problem disappear,everything is ok, so I want to know why?
This is a common problem when pooled connections in longer running applications return connection closed.
The mongoose documentation recommends adding keepAlive to the options object you pass into the connect function.
Here's an example (you can remove replset if you're not using this),
// include keep alive for closing connections,
// http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
var mongoOptions =
{
db: {safe: true},
server: {
socketOptions: {
keepAlive: 1
}
},
replset: {
rs_name: 'myReplSet',
socketOptions: {
keepAlive: 1
}
}
};
mongoose.connect( YOUR_URI, mongoOptions );
mongoose.connection.on('error', function(err) {
console.log('Mongo Error:\n');
console.log(err);
}).on('open', function() {
console.log('Connection opened');
});
mongoose.connect() Is not accepting any callback functions as you have use in your code i.e.your code snippet of mongoose:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/word-sentence",function(err) {
if(err)
console.trace('error occurred, when attempted to connect db. Error: ' + err);
});
So, I recommend you to start with this:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/word-sentence');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
// yay connected!
});
Again you cannot expect any arguments in the callback from db.open('open', function cb(){})
I suggest to go through these quick start, mongoose docs - enlightens how you can jump into source code if some conflict is found in the docs & mongodb/mongoose close connection

Resources