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.
Related
I am currently working with node and mongoDB
here is my code
import dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
mongoose
.connect(
`mongodb+srv://OmniBotBuilder:${process.env.DBPASS}${process.env.DBUSER}.kx2vg.mongodb.net/${process.env.DBNAME}?retryWrites=true&w=majority`,
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
)
.catch(() => console.error("Unable to connect to DB"));
mongoose.connection.on("connected", () => {});
const Schema = mongoose.Schema;
const omniGamesSchema = new Schema({
discordId: Number,
steamId: Number,
});
const omniGamesModel = mongoose.model("omniGamesSchema", omniGamesSchema);
const createNewUser = (discordId, steamId) => {
const newUserMap = new omniGamesModel({
discordId: discordId,
steamId: steamId,
});
newUserMap.save((err) => {
if (err) {
console.error(err);
}
});
};
export { createNewUser };
and the error i am getting is this one
MongooseError: Operation omnigamesschemas.insertOne() buffering timed out after 10000ms
at Timeout. (C:\Users\dahiy\OneDrive\Desktop\bots\omni-games\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
This issue normally is caused because:
wrong auth, by the meaning the mongo path string is wrong so maybe double check your pass and username
check the allowed IP to access the database from the mongo website, if you want it to be accessed from everywhere just use IP: 0.0.0.0/0
Your internet connection might be slow to the point it cannot connect to the DB
Hope you found this helpful! :)
You can open https://cloud.mongodb.com/
Click connect Goto the Connect your application
Select Driver Node.js version 4.1 leter
Copy the link which you have to show than paste this link to your
project .env file now try to run application connect Database and
check.
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.
I face this problem for 2 weeks now ,I was able to connect to my mongodb cluster before but now when i try to connect it give me this error message (queryTxt ETIMEOUT keep-connect-ebnzp.mongodb.net) ,I ask someone to try connect it from his pc and it connected and when i try to connect locally it work fine so what is the problem
I use this url to connect
mongodb+srv://mohamed:<password>#keep-connect-ebnzp.mongodb.net/<dbname>?retryWrites=true&w=majority
mongodb config code
const mongoose = require('mongoose');
const db = process.env.MONGDB_URL;
const mongoDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
console.log('Mongo DB connected');
} catch (err) {
console.error(err);
process.exit(1);
}
};
image for error on my terminal
module.exports = mongoDB;
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
I have created mongodb user with command
use admin
db.createUser(
{
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
}
)
then in my app I am trying to connect mongoose like this
var options = {
user: "superuser",
pass: "12345678"
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';
mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
I am getting this error when inserting data through mongoose
MongoError: not authorized for insert on twitter-mongo.users
please tell me what is wrong in my code
You must declare the authSource parameter in your connection string in order to specify the name of the database that contains your user's credentials:
var options = {
user: "superuser",
pass: "12345678"
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo?authSource=admin';
Note: for users of Mongoose 4.x, you may want to also include useMongoClient: true in your options object. This silences the Please authenticate using MongoClient.connect with auth credentials and open() is deprecated error messages.
This is working fine:
var options = { server: { socketOptions: { keepAlive: 1 } } };
var connectionString = 'mongodb://admin:admin1234#localhost:27017/myDB';
mongoose.connect(connectionString, options);
//Add those events to get more info about mongoose connection:
// Connected handler
mongoose.connection.on('connected', function (err) {
console.log("Connected to DB using chain: " + connectionString);
});
// Error handler
mongoose.connection.on('error', function (err) {
console.log(err);
});
// Reconnect when closed
mongoose.connection.on('disconnected', function () {
self.connectToDatabase();
});
try this
const mongooseConnectionString = 'mongodb://superuser:12345678# localhost/twitter-mongo?authSource=admin'
I did run a mongo service using docker and then connected my mongoose to it with this code
const _database = 'mongodb://user:pass#localhost:port/MyDB?authSource=admin';
mongoose.connect(_database, {
useNewUrlParser: true
})
.then(() => console.log('Connected to MongoDB ...'))
.catch(err => console.error('Could not connect to MongoDB:', err));
this is equal to
mongo --username user --password pass --authenticationDatabase admin --port 27017
on connection and then use MyDB database for doing operations like find, aggregate, insert and etc on it.
if you have no user (MongoDB default user) for your database then you can change Database like bellow:
const _database = 'mongodb://localhost:port/MyDB';
27017 is default MongoDB port if your MongoDB port hasn't changed either then you can do the same for port too.
like bellow:
const _database = 'mongodb://localhost/MyDB';
this is the same as bellow:
mongo
above code is because there is no user and no port then for not been a user there is no need for authentication database either.
mongoose.createConnection('mongodb://username:password#35.238.xxx.xxx:27017/dashboards?authSource=admin', {
useNewUrlParser: true
}, (e) => {
if (e) throw console.error('Error connecting to mongo database master');
console.log('Connected to mongo database master.');
});
You need to create an User in database which you are operating on, not the admin DB.
Use this command,
use twitter-mongo;
db.createUser({
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
});
Instead of this,
use twitter-mongo
db.createUser({
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
});
Correct way to create the connection string is
var connection = mongoose.createConnection("mongodb://username:pwd#hostip:port/dbname?authSource=admin", options);
Please use authSource=admin to authenticate in connection string.