Mongoose is unable to connect to mLab environment - node.js

I have an application I attempting to connect to an mLab environment using Mongoose. I have the following code configured to attempt to connect to an mLab MongoDB Instance.
mongoose.connect(process.env.MONGODB_URI);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {});
The variable process.env.MONGODB_URI is equal to
mongodb://user:password#ds123456.mlab.com:12345/someRandomName (identifiers psuedonymized for privacy).
Applicable Software Versions
Node: v10.7.0
NPM: 6.2.0
Mongoose: 5.2.6
When I try to run the application I get the following error.
node ./bin/www
(node:2555) 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.
connection error: Error: Slash in host identifier
at parseConnectionString (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js:219:15)
at parseHandler (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js:129:14)
at module.exports (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js:25:12)
at deprecated (internal/util.js:70:15)
at connect (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js:179:3)
at connectOp (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js:283:3)
at executeOperation (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/utils.js:420:24)
at MongoClient.connect (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js:168:10)
at Promise (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/lib/connection.js:493:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/lib/connection.js:490:19)
at Mongoose.connect (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/lib/index.js:230:15)
at Object.<anonymous> (/Users/nathanielsuchy/Documents/control-panel/app.js:20:10)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
I am lead to two conclusions. One I need to use the new URL parser, second there's an issue I'm not seeing in my database connection string format. How should I proceed to fix the issue?

The correct format is mongodb://[username:password#]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Does your password contain the '#' or other special chars? If so:
const dbUrl = `mongodb://adminUsername:${encodeURIComponent('adminPassword')}#localhost:27017/mydb`;
Also check this: MongoDB password with "#" in it

Related

Error in connecting Database(MongoDB) with express server

As soon as I am connecting my database with express using
const db = require("./config/mongoose");
It shows error
SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Users\DELL\Documents\Vs Code Folders\Feelare\node_modules\whatwg-url\lib\url-state-machine.js:8:31)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
[nodemon] app crashed - waiting for file changes before starting...
How can I get out of it?
This type of error generally comes when you do not provide valid JSON data.
For ex:-
JSON.stringify({x:})
return error like this
Uncaught SyntaxError: Unexpected token '}'
Please check your provided JSON data again.
And after that you still get error please show your mongoose connection code.
This code is working fine. I have not got any error. I got successful connection message in console Connected to Database:: MongoDB.
Try this code it will also work for you.
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/feelare_db");
const db = mongoose.connection;
db.on("error", console.error.bind(console, "Error in connecting to MongoDB "));
db.once("open", function () {
console.log("Connected to Database:: MongoDB");
});
module.exports = db;

Error Message with MongoDB and Mongoose connection URL malformed, cannot be parsed

I am following a tutorial on creating a Fullstack project Using MongoDB as my database. The tutorial is a bit outdated as it seems MongoDB has updated their process renaming the apps to clusters from what I can see. I tried connecting MongoDB to my server and received URL malformed, cannot be parsed as an error.
EDIT: I removed the images of the code
My server file:
const express = require("express");
const mongoose = require("mongoose");
require("dotenv").config({ path: "variables.env" });
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log("DB connected"))
.catch(err => console.error(err));
const app = express();
const PORT = process.env.PORT || 4444;
app.listen(PORT, () => {
console.log(`Server listening on PORT ${PORT}`);
});
My variable.env file:
MONGO_URI=mongodb+srv://Ernest:<password>#cluster0-ltxeh.mongodb.net/test?retryWrites=true&w=majority
Error Message:
Error: URL malformed, cannot be parsed
at module.exports (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/url_parser.js:17:21)
at connect (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/mongo_client.js:880:3)
at connectOp (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/mongo_client.js:269:3)
at executeOperation (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/utils.js:420:24)
at MongoClient.connect (/Users/eboolo/Desktop/react-recipes/node_modules/mongodb/lib/mongo_client.js:260:10)
at /Users/eboolo/Desktop/react-recipes/node_modules/mongoose/lib/connection.js:427:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/Users/eboolo/Desktop/react-recipes/node_modules/mongoose/lib/connection.js:424:19)
at Mongoose.connect (/Users/eboolo/Desktop/react-recipes/node_modules/mongoose/lib/index.js:208:15)
at Object.<anonymous> (/Users/eboolo/Desktop/react-recipes/server.js:6:5)
at Module._compile (internal/modules/cjs/loader.js:774:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
at Module.load (internal/modules/cjs/loader.js:641:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:837:10)
at internal/main/run_main_module.js:17:11

When i am trying to run this code i am getting the following error

I am trying to connect mongodb database by this code but when running this code I get the error(error at the bottom of the code).
One of the error was in the 7th line where it was resolved by adding
{ useNewUrlParser: true } but still it has more errors. I am using MongoDB version 4.0.1. Do anybody know how to resolve this error.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
app.use(express.static('public'));
app.set('view engine','ejs');
mongoose.connect('mongod://localhost/students', { useNewUrlParser: true });
var studentSchema = new mongoose.Schema({
name: String,
age:Number,
country:String
});
var Student = mongoose.model("Student", studentSchema);
var shashank = new Student({
name:"Shashank",
age:"21",
country:"India"
});
shashank.save((err,student) => {
if(err){
console.log('Something went wrong!');
}
else {
console.log("You added: " + student);
}
});
app.listen(3000,() => {
console.log('Server Listening!');
});
Error while running this code!
D:\HARDWORK\YelpCamp-Course>node app.js
Server Listening!
(node:14060) UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string
at parseConnectionString (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb-core\lib\uri_parser.js:216:21)
at connect (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\operations\mongo_client_ops.js:179:3)
at connectOp (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\operations\mongo_client_ops.js:283:3)
at executeOperation (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\utils.js:420:24)
at MongoClient.connect (D:\HARDWORK\YelpCamp-Course\node_modules\mongodb\lib\mongo_client.js:168:10)
at Promise (D:\HARDWORK\YelpCamp-Course\node_modules\mongoose\lib\connection.js:499:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (D:\HARDWORK\YelpCamp-Course\node_modules\mongoose\lib\connection.js:496:19)
at Mongoose.connect (D:\HARDWORK\YelpCamp-Course\node_modules\mongoose\lib\index.js:229:15)
at Object.<anonymous> (D:\HARDWORK\YelpCamp-Course\app.js:9:10)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
(node:14060) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3) (node:14060) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
mongoose.connect('mongod://localhost/students', { useNewUrlParser: true });
It should start with mongodb://..., And When you use { useNewUrlParser: true } you should always specify the port number in connection string mongoose reference like given below.
mongoose.connect('mongodb://localhost:27017/students', { useNewUrlParser: true });
here port number 27017 is the default port for MongoDB database.
The host you write is not correct, and it should be. m
mongoose.connect('mongodb://localhost:27017/students', { useNewUrlParser: true });
use this two set before connect to moongose more clean and stable for version 5.7
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);
I have faced the same issue, I just started the mongo in the terminal by command
1) sudo service mongod start
2) mongo
worked for me.

URL malformed, cannot be parsed

Here is my error captured:
and here are my coding files:
server file
keys file
I just create connection to mlab using mongodb, node and reactjs. I'm using mongo db version 4.
need your help guys.
[nodemon] starting `node server.js`
Error: URL malformed, cannot be parsed
at module.exports (C:\MERNapps\TestMERN08\node_modules\mongodb\lib\url_parser.js:17:21)
at deprecated (internal/util.js:47:15)
at connect (C:\MERNapps\TestMERN08\node_modules\mongodb\lib\operations\mongo_client_ops.js:179:3)
at connectOp (C:\MERNapps\TestMERN08\node_modules\mongodb\lib\operations\mongo_client_ops.js:283:3)
at executeOperation (C:\MERNapps\TestMERN08\node_modules\mongodb\lib\utils.js:420:24)
at MongoClient.connect (C:\MERNapps\TestMERN08\node_modules\mongodb\lib\mongo_client.js:168:10)
at Promise (C:\MERNapps\TestMERN08\node_modules\mongoose\lib\connection.js:493:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\MERNapps\TestMERN08\node_modules\mongoose\lib\connection.js:490:19)
at Mongoose.connect (C:\MERNapps\TestMERN08\node_modules\mongoose\lib\index.js:230:15)
at Object.<anonymous> (C:\MERNapps\TestMERN08\server.js:12:2)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
(node:3696) 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.
server running on port 5000
The issue is with your keys. Try using:
module.exports= {
mongoURI : "your-uri-string",
options:{key:value}
}
And use the keys as:
mongoose.connect(db.mongoURI,options);
a very common error with MongoDB atlas. better still follow this procedure
Install Mongo DB compass
use Default setting
hostname: localhost & port 27017
create a database with the project name and then collection: user
Connect with the code below on entry js. route
mongoose.connect('mongodb://localhost/projectname')
.then(() => console.log('mongo db working'))
.catch(err => console.log('ERROR is', err))

TypeError: connection.model is not a function in mongoose-auto-increment

I tried to connect mongodb. But I couldn't it. I thought [autoIncrement.initialize] is problem, but I couldn't solve the problem. This is my code.
const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
require('dotenv').config();
mongoose.Promise = global.Promise;
const connect = mongoose.connect(process.env.MONGODB_URI);
autoIncrement.initialize(connect);
Here is error traceback:
/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:27
throw ex;
^
TypeError: connection.model is not a function
at Object.exports.initialize (/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:10:34)
at Object.<anonymous> (/Users/loo/Projects/example-app/app.js:8:15)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
As You read example in this link
You would see this:
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
In fact .connect and .createConnection are different things.
Due to documentation here which says:
Mongoose creates a default connection when you call
mongoose.connect().
You can access the default connection using
mongoose.connection.
that means mongoose.connect does not return connection and You can get that connection using mongoose.connection.
Solution:
mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true})
.then(() => {
console.log('Connected to DB');
})
.catch(error => {
console.error('Connection to DB Failed');
console.error(error.message);
process.exit(-1);
});
autoIncrement.initialize(mongoose.connection);
or You can create a connection as here:
const connection = mongoose.createConnection(process.env.MONGODB_URI);
autoIncrement.initialize(connection);

Resources