Connecting to the mongodb - mongodb

I'm new in the MEAN developing, I'm developing a simple app, and for my first step I'm trying to connect to my mongodb, so I installed node, express, morgan,mongodb, mongoose.
So here is my code in index.js:
const express = require('express');
const morgan = require('morgan');
const app = express();
const { MongoClient } = require('./database');
// Settings
app.set('port', process.env.PORT || 3000);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
// Routes
// Starting the server
app.listen(app.get('port'), () => {
console.log('server on port', app.get('port'));
});
and then the code on my database.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log("horrorrrrrr");
// perform actions on the collection object
client.close();
});
module.exports = MongoClient;
I also try this code that is on the mongodb page to connect to the application:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Of course I change the password to the real one. Please keep in my today it's my first time I touch mongodb and also the MEAN full stack, and I spent too many hours stuck in this connection.
this is the error I get:
(node:5284) 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.
EDIT
#iLiA thanks for your reply ! I tried your code and ain't working, I will show you how I did it with the real password :
const url = 'mongodb+srv://duke:password#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority';
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is not a problem with ${err.message}`);
process.exit(-1)
})
module.exports = mongoose;
and the error is :
there is not a problem with Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Kind regards,

I am confused about why do you downloaded both mongodb and mongoose but here is mongoose solution
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is a problem with ${err.message}`);
process.exit(-1)
})
EDIT:
As it seems you forgot to whitelist your IP address in mongo atlas.

Related

Mongo DB Connection - Password contains unescaped characters

I am trying to connect to MongoDB but I am getting the "Password contains unescaped characters" error. I have included the useNewUrlParser:true option but I still get the error
See my code below:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
connectDB().catch(err => console.log(err));
async function connectDB() {
await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
})
.then(() => console.log("DB Connection Success"))
.catch((err) => console.log(err));
}
app.listen(8800, () => {
console.log("Backend Server is running");
});
Same problem here... solved with encodeURIComponent on the part of the string that had the password
const uri = "mongodb+srv://username:" + encodeURIComponent("pass#") + "#cluster.yijnb.mongodb.net/db?retryWrites=true&w=majority";
Maybe provide username and password as option:
const options = {
user: <username>,
pass: <password>,
authSource: "admin",
useNewUrlParser: true
};
mongoose.connect(process.env.MONGO_URL, options);
I solved it by changing the password as I tried using several fixes to help me connect with the initial password that contained ".".

Cannot connect to MongoDB - Authentication Failed

Having an issue connecting to MongoDB when starting a new MERN stack project:
server.js code:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
.env file:
ATLAS_URI = mongodb+srv://exampleUser:exampleUserPassword#cluster0.y9bpc.mongodb.net/example-
database?retryWrites=true&w=majority
receiving error:
(node:23036) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
Not sure what I'm doing wrong here, was just following a tutorial. Only difference from the tutorial is the connection string which also requires a dbname which I created and added. I'm hoping it's something more simple than that. I appreciate any help.
So it appears that I chose to add my own IP address instead of allowing access from anywhere and that was the issue. Hooray!

Getting MongoParseError: Invalid message size: 1347703880, max allowed: 67108864

I am building a RESTful BLogAPP where my stack is MEN
while connecting to mongo server i am getting this error
These were working But this happened
My Mongo file code
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = "mongodb://localhost/127.0.0.1:27017/Blog";
mongoose.connect(url ,{
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", url);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
module.exports = mongoose;
My app.js
const mongoose = require("./server/mongoose");
It was resolved for me after remove server port from connection string. Replace mongodb connection string From
const url = "mongodb://localhost:27017/Blog";
To
const url = "mongodb://localhost/Blog";
I got the same error message and I've finally solved it. Try to leave it like this:
const url = "mongodb://localhost:27017/Blog";
I too got the same error while accessing MongoDB via mongoose.
The URI I set was MONGO_URI=mongodb://localhost:3000/myDB.
The port was wrong.
I solved it by correcting the Mongo URI.
MONGO_URI=mongodb://localhost:27017/myDB.

mongoDB, mongoose, cannot connect to DB

First time using mongoDB. Trying to connect to my cluster that i just created on atlas however i keep getting errors
keys.jss
module.exports = {
mongoURI: 'mongodb+srv://john:<********>#mern-shopping-i5abd.mongodb.net/testretryWrites=true&w=majority'
};
I might be following an outdated tutorial so certain things might be 'unnecessary'
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
// Connect to Mongo
mongoose
.connect(db, {useNewUrlParser: true} )
.then(() => console.log('monogoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server started on port ${port}'));
Rather than displaying port '5000' i would get an error (different each time)
message: '3rd parameter to mongoose.connect() or mongoose.createConnection() must be a function, got "object"',
name: 'MongooseError'
Here is how it would look with a function as a callback, instead of using promises. Notice that I also moved the app startup inside the callback function. This ensures that the app only starts up when we successfully connect to the DB.
I also moved the DB options (2nd parameter in the connect method), into a variable. This way, it's easy to find and can be modified in one place, if necessary. Ideally, you'd keep all your DB config in a single file, and reference it in other files as needed. Separate concerns :)
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect(db, dbOptions, function(error) {
// we had an error of some kind
if (error) {
console.error(error);
// better yet, we don't want to app to run without our DB!
throw error;
}
// If we made it here, no errors came up
console.log('monogoDB Connected...');
// Start up the app!
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
});
Here is how it would look with the promise structure:
const express = require( "express" );
const mongoose = require( "mongoose" );
const bodyParser = require( "body-parser" );
const app = express();
// Bodyparser Middleware
app.use( bodyParser.json() );
// DB config
const db = require( "./config/keys" ).mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect( db, dbOptions )
.then( () => {
console.log( "monogoDB Connected..." );
// Start the application
const port = process.env.PORT || 5000;
app.listen( port, () => {
console.log( `Server started on port ${port}` );
} );
} )
.catch( err => {
console.log( err );
throw err;
} );

winston-mongodb log connection fails

My express web app uses Winston for logging, and the logs are saved to a mongolab hosted mongoDB (replica set) using winston-mongodb.
Everything was working fine for a few days, then when traffic picked up a bit the logs just stopped saving/connecting to the DB. Unfortunately this means I have no logs to check to see what went wrong - a frustrating situation. Everything else is still working fine - other collections (like users) are saving and updating correctly, the server is up.
I've tried redeploying/restarting the server to no avail, the logs won't start recording again. I suspect there is some nuanced problem with my server/logger setup, possibly a race condition related to the DB connection, but I'm really lost right now. Here's the code:
//server.js (simplified required modules - only ones possibly relevant to question)
var express = require( 'express' );
var session = require('express-session');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var mongoose = require( 'mongoose' );
var uriUtil = require('mongodb-uri');
var config = require('config');
var bodyParser = require('body-parser');
var MongoStore = require('connect-mongostore')(session);
var logger = require('./logs/logger.js');
// DATABASE CONNECT
var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } };
var mongodbUri = "mongodb://<user>:<pw>#ds012345-a0.mongolab.com:12345,ds012345-a1.mongolab.com:12345/<db>"
//use mongo-uri to make sure url is in the correct format
var mongooseUri = uriUtil.formatMongoose(mongodbUri);
mongoose.connect(mongooseUri, options);
var conn = mongoose.connection;
// __Create server__
var app = express();
conn.on('open', function(e) {
var sessionStore = new MongoStore({ mongooseConnection: mongoose.connections[0] });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
store: sessionStore,
secret: config.session.secret,
cookie: {
maxAge: config.session.maxage,
httpOnly: true,
secure: false
//If I set 'secure:true', it prevents the session from working properly.
},
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use( express.static( path.join( __dirname, 'site') ) );
//Routes
app.use('/api/forgot', controllers.forgotpw);
//etc.
});
conn.on('connected', function(){
//Start server
app.listen(config.port, function() {
logger.info( 'Express server listening on port %d in %s mode', config.port, app.settings.env );
logger.info(process.env.NODE_ENV);
});
});
//logger.js
var winston = require('winston');
var config = require('config');
require('winston-mongodb').MongoDB;
if (process.env.NODE_ENV == 'production') {
var winston = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'warn' }),
new (winston.transports.MongoDB)({
//db : 'atlas_database',
level : 'debug',
//ssl : true,
dbUri : "mongodb://<user>:<pw>#ds012345-a0.mongolab.com:12345,ds012345-a1.mongolab.com:12345/<db>"
})
]
});
winston.info('Chill Winston, the logs are being captured with production settings');
}
module.exports = winston;
Any thoughts on what is causing the logs to no longer function would be greatly appreciated.
When Winston establishes a connection to a Mongo instance, it looks specifically for the replicaSet flag to determine if the connection is a replica set. Otherwise, it connects to the first host in the dbUri. ( Source: https://github.com/indexzero/winston-mongodb/blob/master/lib/winston-mongodb.js#L28 )
To have configure Winston with a connection that will properly handle failovers, use the following URI:
dbUri : "mongodb://<user>:<pw>#ds012345-a0.mongolab.com:12345,ds012345-a1.mongolab.com:12345/<db>?replicaSet=<replsetname>"
If you ever want to test your code to verify that it can handle a replica set failover gracefully, you can use a testing cluster called flip-flop described here: http://mongolab.org/flip-flop/
(Full Disclosure: I work for MongoLab.)