Problems connecting to MongoDB server from MongoLab - node.js

I'm trying to connect to mongodb created by MongoLab, but it always seems to fail.
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>#ds123854.mongolab.com:12345/the_db');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
});
mongoose.connection.on('error', function (err) {
console.log('Could not connect to mongo server!');
console.log(err);
});
// check if mongoose connected; 0 = no; 1 = yes; 2 = connecting; 4 = disconnecting
console.log("mongoose connection: " + mongoose.connection.readyState);
I get the log:
mongoose connection: 2
Could not connect to mongo server!
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
I tried to check the password, so I did the following in my console:
> mongo ds123854.mongolab.com:12345/the_db -u <dbuser> -p <dbpassword>
MongoDB shell version: 3.0.7
connecting to: ds123854.mongolab.com:12345/the_db
rs-ds123854:PRIMARY> db.mynewcollection.insert({ "foo": "bar"})
WriteResult({ "nInserted" : 1 })
rs-ds123854:PRIMARY> db.mynewcollection.find()
{ "_id" : ObjectId("563c1913504f0ab5cb96d74c"), "foo" : "bar" }
The username and password seem right and I can see that the insert command did put something into the database.
I am hosting my server in localhost, so I believe that's the problem. What sort of things am I missing in my configuration?

Solution: Ensure that your version of Mongoose is up to date.
In my case, I was using version 3.6.13, but the current version is 4.2.4
If you specified your mongoose version, just update your package.json file and use command line npm update

Related

Failed to connect node.js app to MongoDB Atlas despite using the correct connection credentials

I'm trying to connect my node.js application to MongoDB Atlas but I keep getting a "Bad authentication error" and yes, I am using the current database user credentials.
Here is the snippet that's supposed to connect to MongoDB Atlas
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
console.log('MongoDB Connected: ' +conn.Connection.host)
}catch (err) {
console.error(err)
process.exit(1)
}
}
My terminate shows me bad authentication and some key-pairs that look so:
{
ok: 0,
code: 8000,
codeName: 'AtlasError',
name: 'MongoError'
}
Any ideas why it is not connecting to MongoDB Atlas?
I finally singled out the problem, it was the MongoDB connection string. I was simply inserting my password in the password field without removing the angle brackets.

Getting error while connecting to mongoDB database using Node.js

I am getting the following error while connecting the mongoDB database present in MLAB using Node.js.
Error in DB connection : {
"name": "MongoNetworkError",
"errorLabels": [
"TransientTransactionError"
]
}
Here is my code:
var mongoose = require('mongoose');
const authData = {
"useNewUrlParser": true,
"useCreateIndex": true
};
//connecting local mongodb database named test
mongoose.connect(
'mongodb://subhra:*****#ds139989.mlab.com:39989/hlloyd',
{useCreateIndex: true, useNewUrlParser: true,useUnifiedTopology: true },
(err)=>{
if (!err)
console.log('MongoDB connection succeeded.');
else
console.log('Error in DB connection : ' + JSON.stringify(err, undefined, 2));
}
);
module.exports = mongoose;
Here my database is present inside MLAB but when I am tring to connect to that DB its throwing me that error. I need to connect to my database here.
"useCreateIndex": true and useUnifiedTopology: true is deprecated .
Try out the following code to connect your mongoDB database .
mongoose.connect('mongodb://subhra:*****#ds139989.mlab.com:39989/hlloyd', {useNewUrlParser: true})
.then(() => console.log("Connected"))
.catch(err => console.log(err));
module.exports = mongoose;
Please add your current IP or 0.0.0.0 to whiteList following "main page > security section > network access > add IP" in MongoDB website.
I hope this helps.

db.collection is not a function

I am trying to simply insert an entry in a MongoDB collection using Nodejs. Here is my code:
code:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');
db.collection('Todos').insertOne({
text: 'Something to do',
completed: false
}, (err, result) => {
if (err) {
return console.log('Unable to insert todo', err);
}
console.log(JSON.stringify(result.ops, undefined, 2));
});
db.close();
});
When I run the code, it showing the following error:
error:
TypeError: db.collection is not a function
Uninstalling existing mongodb package and reinstalling using the following commands resolved the issues
npm uninstall mongodb --save
npm install mongodb#2.2.33 --save
Version MongoDB >= 3 - That database variable is actually the parent object of the object you are trying to access. If u using mongo 3+:
const myDb = db.db('YourDatabase')
myDb.collection('YourDatabase).insertOne ....
you can rewrite your code as follow
MongoClient.connect(url,(err,db) =>{
const database= db.db('TodoApp')
database.collection('Todos').insertOne({})
}
The reason for this error is the version of the NodeJs Driver. TypeError: db.collection is not a function. If the version is > 3.0.1 then you have to change the db to client. For more info check this page, it helped me!
[db.collection is not a function when using MongoClient v3.0
Hope that helps!

Node.js MongoError: auth failed

I found out my website wasn't working anymore because i can't auth to my mongolab DB.
here is my code (it used to work for months):
var mongoose = require('mongoose');
mongoose.connect('mongodb://USER:PASSWORD#ds053419.mongolab.com:53419/jobinfest',
function(err) {
console.log(err);
if (err) { throw err; }
}
);
I have this error:
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
But i can access the db via mongolab and :
mongo ds053419.mongolab.com:53419/jobinfest -u USER -p PASSWORD
I tried to create new users, even a new db. This way of connection seems to not work anymore
In your code be sure you are replacing USER:PASSWORD with your actual username and password.
mongodb://USER:PASSWORD#ds053419.mongolab.com:53419/jobinfest

Unable to connect to MongoDB using node.js

I installed MongoDB in my machine and I'm able to start mongod and connect to the db using the mongo command. I even imported some data in the mycol collection of the mydb db:
$ sudo start mongodb
mongodb start/running, process 31008
$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use mydb
switched to db mydb
> db.mycol.count();
5730
> ^C
bye
But now if I want to access the db via node.js it doesn't work anymore, I get a TypeError.
I try this code (UPDATED):
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/mydb', function(err, db) {
if(err) throw err;
console.log("connected!");
});
This is based on the npm module mongodb, I also tried mongoose and mongojs, each time with the same result. As soon as I want to connect to the database, I get a TypeError.
$ node mngclient.js
Failed to load c++ bson extension, using pure JS version
events.js:172
throw TypeError('type must be a string');
^
TypeError: type must be a string
at TypeError (<anonymous>)
at EventEmitter.once (events.js:172:11)
at Server.Base._registerHandler (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/base.js:387:23)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/server.js:410:12)
at EventEmitter.emit (events.js:91:17)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:111:15)
at EventEmitter.emit (events.js:97:17)
at Socket.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection.js:297:10)
at Socket.EventEmitter.emit (events.js:116:20)
at Object.afterConnect [as oncomplete] (net.js:848:10)
UPDATE:
The version of the mongodb npm package is 1.3.23
npm outdated shows no output, so I guess my packages are up-to-date
Using mongoose with the following very simple code brings up the exact same error:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
UPDATE II:
I still couldn't resolve this issue on my machine
I setup the whole project in a virtual machine using vagrant. It works like a charm.
You should read the document , your trying to start a server(I'm not sure why?) here is an example on connecting to the mongo database you already have running :
MongoClient.connect('mongodb://localhost:21017/myDb', function(err, db) {
"use strict";
if(err) throw err;
...//your code
});
Step 1: npm install mongodb
Step 2: create a file, name it suppose : app.js
Paste the following content into the file:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'myDB';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
Step 3 : node app.js
Step 4: run mongod and mongo, check updated db list using show dbs
Database will be created and a collection named 'documents' will be added over there.

Resources