I have server.js and db.js The db.js file interacts with my database using Mongoose and I use server.js to call functions from db.js :
var mongoose = require('mongoose');
mongoose.connect('', { useNewUrlParser: true })
var Schema = mongoose.Schema;
module.exports = function () {
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
return db.once('open', function() {
console.log("Connected to DB")
var postschema = new Schema({
title: String,
intro: String,
body: String,
author: String,
timestamp: { type: Date, default: Date.now }
});
var post = mongoose.model('post', postschema);
return {
newPost(title, intro, body, author) {
var newpost = new post({
title: title,
intro: intro,
body: body,
author: author
})
},
getPostsAll() {
post.find({}, function (err, res) {
return (`Error:${err} Posts:${res}`)
})
}
}
})
}
And my server.js calls three functions from db.js :
var DB = require('./db.js')
var db = DB()
db.getPostsAll()
db.newPost()
I don't understand why I get this error :
connection error: { MongoNetworkError: connection 4 to black-test-shard-00-01-ewyaf.mongodb.net:27017 closed
at TLSSocket.<anonymous> (E:\HTML\black-box\node_modules\mongodb-core\lib\connection\connection.js:276:9)
at Object.onceWrapper (events.js:272:13)
at TLSSocket.emit (events.js:185:15)
at _handle.close (net.js:541:12)
at TCP.done [as _onclose] (_tls_wrap.js:379:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
What am I doing wrong? I found an article but can't make anything of it.
I had
'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]:
I added my current IP to whiteList following "main page > security section > network access > add IP" in MongoDB website.
I hope this helps.
What is a TransientTransactionError
A TransientTransactionError is a transactional error that is classified as temporary, and if retried it may be successful. Furthermore, a TransientTransactionError write conflict occurs prior to a commit when no write lock has been taken and the transaction (new data) is not reflected in the transaction snapshot (previous data.) As a result, these errors are completely safe to retry until there is a successful commit.
Transactions that retry in this scenario are retried from the beginning of the transaction.
Keep in mind This error label is different than commit errors that happen when the lock has been taken but the transaction can't complete its commit. The error label for this is UnknownTransactionCommitResult. The reference to this is notable due to the difference in understanding where in your application an error is occurring and what may be the underlying cause and how the application can and or will respond due to different error types.
If you're using MongoDB supported drivers, there are two possible cause the code is getting this error:
Any database command error that includes the "TransientTransactionError" error label in the "errorLabels" field.
Any network error encountered running any command other than commitTransaction in a transaction.
The code example in MongoDB Transactions: retry-transaction show cased how to handle TransientTransactionError.
If the error message is MongoNetworkError, it means the transient transaction error is related to the network connectivity between the client and the server. This could either be a one time network glitch which is retry-able, or there is no network access which require network configuration. If the error is encountered on the first time the client trying to access the server, it is likely that there is network configuration needed. If the server is on MongoDB Atlas, please see Configure Whitelist Entries.
Go to your mongoDB Atlas Dashboard
Open Network Access (its there in side navbar)
Click on ADD IP ADDRESS
Click on allow from Any IP Address ( it basically give access to your dynamic IP address)
Now you are done.
If there is no security issue and you are just doing it for connecting:
While setting up the IP Whitelist; format should be 0.0.0.0/0 , you will not face the issue.
Moreover, as you have answered yourself, we can add the ip for which we need access.
I had the same issue/error, albeit on a Windows machine. Even though I thought I had started the mongodb service, I didn't see it running in Windows Services. So, I manually started the mongoDB service inside Services and then the error went away. Hope this helps!
I encountered this error when running the populatedb.js script in the MDN tutorial for Express/NodeJS.
The script was looking for a db connection starting with mongodb://, however my connection string from mongo started with mongodb+srv://.
I edited the script to check for this syntax instead, which resolved the error.
I hope this helps someone.
I had similar problem...
All day I was able to connect via mongoose. Then bang I started getting 'TransientTransactionError' error. I could connect to mongoDB via shell so I knew the server was up and running as expected.
IPv6/localhost. My IP switched from IPv4 to IPv6. I resolved the issue by disabling IPv6 and getting regular IPv4 IP.
EDIT -- seems I can reliably re/create this issue by connecting to 'localhost' while my NIC is configured with a IPv6 IP. Changing localhost->127.0.0.1 seems to resolve the issue.
Make sure the server didn't run out of storage space.
In my case, none of the suggested answers helped. I was pulling out my hair until I've noticed that the server ran out of storage space. Clearing up a few megabytes of storage solved the error immediately.
The TransientTransactionError actually makes sense in this scenario due to its nature of being a temporary error that could be resolved upon an explicit retry - though it did take me a while to figure out it had to do with a storage issue.
For me, the transient transaction error came whenever I switched from my wifi network to my phone's hotspot. If this happens to you too, go to MongoDB website where you have made your database and white list your current IP address again. This will solve your problem.
If you are using MongoDB Atlas. You need to Whitelist your IP address on the Atlas Console in the security settings.
If you still have this error, another reason is that you forgot to restart nodemon server after changing config file. CTRL+C and start again, that's how i solved it.
Security > Network Acess> Add IP Adress > Add Current Computer IP address.
Solved my problem.
Using mLab -- When your cluster is created, you need to add a database user (under the users tab) and make sure to not click the Make read-only checkbox. Once I did this, the errors went away. I was getting the same errors as above. The database user can be your login user name and password.
Go to your MongoDb Atlas dashboard. Click on Network Access, Click on add Ip Address and allow connectivity from any Ip Address.
This should solve your problem.
I had this problem when trying to connect my Heroku app to a MongoDB Atlas database.
If you do a on you terminal
heroku logs --tail
You might see
ERROR: { MongoNetworkError:
connection 4 to cluster0-shard-40-01-qnwp8.mongodb.net:27017 closed
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }`
After whitelisting the server connection on MongoDB Atlas, the database connection error was resolved.
You can read about the error online but the solution for this problem is: go to you MongoDB atlas and add your IP address.
Go to:
main page > security section > network access > add IP
This problem is basically when the architecture do not know your own IP address.
Also, copy-paste directly to google to get straight forward solution.
Related
I'm trying to send RabbitMQ messages from my host machine to a Minikube instance with a RabbitMQ cluster deployed.
When running my send script, I get hit with this error:
Handshake terminated by server: 403 (ACCESS-REFUSED) with message "ACCESS_REFUSED - Login was refused
using authentication mechanism PLAIN. For details see the broker logfile.
In the broker logfiles I can see this line:
Error on AMQP connection <0.13226.0> (172.17.0.1:40157 -> 172.17.0.8:5672, state: starting):
PLAIN login refused: user 'rabbitmq-cluster-default-user' - invalid credentials
I'm sure I have the correct credentials since I got them directly from the RabbitMQ pod, following the official documentation (link).
My send script is below:
const amqp = require('amqplib/callback_api');
const cluster = "amqp://rabbitmq-cluster-default-user:dJhLl2aVF78Gn07g2yGoRuwjXSc6tT11#192.168.49.2:30861";
amqp.connect(cluster, function(error0, connection)
{
if (error0)
{
throw error0;
}
connection.createChannel(function(error1, channel)
{
if (error1)
{
throw error1;
}
const queue = "files";
var msg = {
name: "Hello World"
};
var msgJson = JSON.stringify(msg);
channel.assertQueue(queue, {
durable: false
});
channel.sendToQueue(queue, Buffer.from(msgJson));
});
});
I know the code works as I ran the exact same script for my localhost setup and it worked. The only thing I've changed is the URL (for the Minikube RabbitMQ service).
I've seen a few other posts that contain a similar issue but most solutions are about including the correct credentials in the URI, which I have done.
Any other ideas?
You can use port forwarding the rabbitMQ service to your local machine and use UI login and check the password with the UI given by the RabbitMQ itself.
kubectl port-forward svc/rabbitmq UI-PORT:UI-PORT (must be 15672)
then from a browser
localhost:15762
must be enough
For clearance you can check if you can login from the container itself. If the login from the container fails you can also check the yaml file or the helm chart you are using for login methods and credentials. Plain login may be disabled.
Another situation may be with the distrubution. When deploying RabbitMQ I try to use bitnami charts. I can suggest them.
If all these fails there is another way you can use. You can try to create another user with admin privileges to connect to RabbitMQ and then keep using it.
For more information, you can post container/pod logs for us to see.
Good day.
I'm learning Node.js and just started working with MongoDB.
I'm making a connection with the MongoDB Cluster I've created
const dbURI = 'mongodb+srv://testuser:test1234#nodelearning.fzofb.mongodb.net/mydb?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log('connected to db'))
.catch((err) => console.log(err));
When I run it nodemon app I get this error:
Error: querySrv ENOTFOUND _mongodb._tcp.mydb.fzofb.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:206:19) { errno: undefined, code: 'ENOTFOUND', syscall: 'querySrv',
hostname: '_mongodb._tcp.mydb.fzofb.mongodb.net' }
Also if you have your mongodb Atlas cluster inactive after a while. It could get paused and then when you run a server it returns the error you had.
So another bet is to login to your Atlas account and confirm if it hasn't been paused. Well this option of mine should only be considered after trying the options above.
The error indicates that there is no error in the code. This leaves you with three potential possibilities:
Ensure you have MongoDB installed on your computer.
Make sure you're connected to wifi that is not public.
Make sure you have allowed the IP in network access of MongoDB as shown in the image below:
In my case, I was connected to public wifi in a coworking space. I change my connection to my personal hotspot and it worked.
Try disabling VPN if enabled. It helped me.
You need to convert special characters in connection string password to percent encoding.
I had the same issue with mongodb-compass. For me it was incorrect connection string format. So in my case it required to convert # symbol in my password to %40 (percent encoding).
You can read more about this in here. and here.
I had the same issue. I was using the latest srv string. I don't know if this will help you. But using the olderve
mongodb://<username>:<password>#cluster0-shard-00-00.2pznz.mongodb.net:27017,cluster0-shard-00-01.2pznz.mongodb.net:27017,cluster0-shard-00-02.2pznz.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-s5orlv-shard-0&authSource=admin&retryWrites=true&w=majority```
This error happens if the IP Address you try to access the database with is not on the IP Access List. Go to MongoDB Login and under security click on the Network Access and check if your IP is added there.
In my case, the problem got solved when I sign in to my MongoDB atlas account.
In my case, I was re-using a string connection from another project.
I copied my original string connection from MongoDB site and worked fine.
FIX : : previously my cluster password was "chaudhary#786" which contained the
special character "#", due to which the compass string connecting
compiler got confused hence in the next turn I changed my password to
"gghjkl98", i.e without any special characters. and I got connected
without any errors.
SOLUTION : password of the cluster should not contain characters like \backslash
or # or any other characters
I have set up a mongodb Atlas free tier cluster. When I try to connect to it with node js, it throws an error. I have white listed my IP both manually and with select current. I have also tried adding +srv to my connection url but that just causes more errors.
Here is the node js code I was trying to connect with
const { MongoClient } = require("mongodb");
const url = "mongodb://user1:password1!#cluster0-shard-00-00-bc7dh.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true";
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
} catch (err) {
console.log(err.stack);
}
finally {
await client.close();
}
}
run().catch(console.dir);
and here is the error I get
MongoServerSelectionError: connection to 52.64.0.234:27017 closed
at Timeout._onTimeout (C:\Users\YOUNG\node_modules\mongodb\lib\core\sdam\topology.js:430:30)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
people with a similar problem were able to solve it by whitelisting their ip addresses, but it hasn't worked for me. What could possibly be the problem?
I have tried allowing access for all ips but the error persists and when I use the uri with +srv, I get the following error
MongoServerSelectionError: Authentication failed.
at Timeout._onTimeout (C:\Users\YOUNG\node_modules\mongodb\lib\core\sdam\topology.js:430:30)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
It is because your IP address is not whitelisted .
Go to network access in your mongodb atlas in your project and ADD IP ADDRESS . to test just add access from anywhere option
there you go get back and try again with the connection string .
Go to your network access at your cluster in MongoDB
Go to network access in mongo db and add in the Ip address 0.0.0.0, and everything will be okay.
You are missing tls=true URI option in the connection string.
You should also use the SRV URI that is provided by Atlas by default which takes care of this.
const client = new MongoClient(uri,
{
useNewUrlParser: true,
useUnifiedTopology: true,
});
client.connect(() =>
{
your_collection = client.db('your_db_name').collection('collection_name')
})
This worked for me.
I also had the same problem you encountered and found out the IP address is not correct which is set in "Network Access".
Try the followings:
Go to your MongoDB Atlas Project page
Click "Network Access"
Click "ADD CURRENT IP ADDRESS" button (it's very useful!)
Click "Confirm"
And now, the right IP address to connect with your PC is shown in IP Access List.
That's all!
You can fix the issue in a few steps.
For me this error was occurring because my connection string was wrong.To be very specific - I copied the sample connection string from a course I was learning and just replaced the username and password with my credentials. So, the credentials were right but not the rest of the connection string.
Just for the sake of understanding. Please see below :
mongodb+srv://myusername:mypassword#courseproject.h1mpg.mongodb.net/?retryWrites=true&w=majority"
myusername and mypassword are correct i.e belongs to the cluster in my MongoDB atlas account, but the rest of the string is wrong as I copied it from somewhere instead of copying it from my own MongoDB atlas account.
So please make sure to double check if your entire connection string is correct.
There is a very simple and straight forward fix for this issue,
Goto your mongodb account dashboard,
Enter Network Access
Where you see add IP Address, add a global address, thats is access from anywhere.
The images below better illustrates this procedue
And thats its, your done
For Cloud DB Server:
This problem mainly occurs if you're using online cloud storage. This is because you are not adding the IP address correctly. Here you can add the IP address as 0.0.0.0 as shown in the figure. If you add an IP like this, it will auto-import your machine IP address.
Trying to set up MongoDB for my Node.JS application. I running this command:
mongo "mongodb+srv://cluster0-gjc2u.mongodb.net/test" --username <myusername>
And getting this response every single time.
MongoDB shell version v4.2.1
Enter password:
connecting to: mongodb://cluster0-shard-00-00-gjc2u.mongodb.net:27017,cluster0-shard-00-01-gjc2u.mongodb.net:27017,cluster0-shard-00-02-gjc2u.mongodb.net:27017/test?authSource=admin&compressors=disabled&gssapiServiceName=mongodb&replicaSet=Cluster0-shard-0&ssl=true
2019-12-07T12:14:39.630-0600 I NETWORK [js] Starting new replica set monitor for Cluster0-shard-0/cluster0-shard-00-00-gjc2u.mongodb.net:27017,cluster0-shard-00-01-gjc2u.mongodb.net:27017,cluster0-shard-00-02-gjc2u.mongodb.net:27017
2019-12-07T12:14:39.630-0600 I CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to cluster0-shard-00-00-gjc2u.mongodb.net:27017
2019-12-07T12:14:39.631-0600 I CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to cluster0-shard-00-01-gjc2u.mongodb.net:27017
2019-12-07T12:14:39.631-0600 I CONNPOOL [ReplicaSetMonitor-TaskExecutor] Connecting to cluster0-shard-00-02-gjc2u.mongodb.net:27017
2019-12-07T12:14:40.259-0600 I NETWORK [ReplicaSetMonitor-TaskExecutor] Confirmed replica set for Cluster0-shard-0 is Cluster0-shard-0/cluster0-shard-00-00-gjc2u.mongodb.net:27017,cluster0-shard-00-01-gjc2u.mongodb.net:27017,cluster0-shard-00-02-gjc2u.mongodb.net:27017
2019-12-07T12:14:40.799-0600 I NETWORK [js] Marking host cluster0-shard-00-00-gjc2u.mongodb.net:27017 as failed :: caused by :: Location40659: can't connect to new replica set master [cluster0-shard-00-00-gjc2u.mongodb.net:27017], err: AuthenticationFailed: bad auth Authentication failed.
*** It looks like this is a MongoDB Atlas cluster. Please ensure that your IP whitelist allows connections from your network.
2019-12-07T12:14:40.800-0600 E QUERY [js] Error: can't connect to new replica set master [cluster0-shard-00-00-gjc2u.mongodb.net:27017], err: AuthenticationFailed: bad auth Authentication failed. :
connect#src/mongo/shell/mongo.js:341:17
#(connect):2:6
2019-12-07T12:14:40.803-0600 F - [main] exception: connect failed
2019-12-07T12:14:40.804-0600 E - [main] exiting with code 1
I have whitelisted my IP address and made sure everything is in order. What could be causing this problem and how could I fix it? Why would this problem be occurring?
What I tried was:
Create new user
Made sure the username and password for my mongoURI when connecting my application is the same as the username and password for when I connect with the mongo shell.
Run your connection string in your command line in your application.
I realise that "just wait a bit" isn't a terribly constructive answer, but I had the same issue and no luck in finding a solution, so left it for a couple hours and came back to find it working perfectly.
The text that says your change has been deployed is misleading. Not sure why it takes several hours to kick in, but for reference I found this when using the M0 Sandbox cluster tier.
So you have to take care of 2 things.
1) First off, having mongodb in your $PATH, create a .bash_profile under the home folder if you don't have it already, then insert the following.(For Ubuntu)
export PATH="$PATH:/usr/bin/mongo"
Make sure you place the location of mongo on your computer. If you don't know the location, type whereis mongo on the terminal.
After saving, type source ~/.bashrc in the terminal.
2) Lastly, copy the connect link from the mongodb atlas, and when asked for username and password
please provide the credentials set to access the database not the mongdb atlas account.
This resolution might be specific for the mLabs to MongoDB Atlas migration tool provided by Cloud MongoDB.
My resolution was to:
Re-create the user with the same user name
Change from spesific mLabs grants to Atlas built-in roles
Set new credentials, I also avoided using special chars.
Good luck!
Create a simple password which doesn't have any special characters, it only includes alphabets and numbers.
I wasn't able to access but changing password worked for me.
I've followed a React-native login tutorial using Firebase, I use create-react-native-app for easy dev(my package.json), I'm using NodeJS v6.10.1, I'm using Note 4 Device(4.4.4), I enabled Email/Password authentication within Firebase console, for some reason I get:
{
code: "auth/network-request-failed",
message: "A network error (such as timeout, interrupted connection or unreachable host) has occurred."
}
I didn't forgot to use firebase.initializeApp and my code is:
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(e0 => {
console.log(e0);
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(e1 => {
console.log(e1);
this.setState({ error: 'Authentication Failed.' });
});
});
For both I get the same error object.
So the problem was:
It all starts by this Debugger and device times have drifted by more than 60s, due to other, adb related problem I couldn't run adb shell "date -sdate +%m%d%H%M%Y.%S", after I fixed my adb problem I run adb shell "date -sdate +%m%d%H%M%Y.%S", now the Firebase error was saying: such as timeout, adb(my computer) time was -4min than the device, so to fix that I changed the time on my computer, adding 4min so it will match the device time.
What I assume was the problem, I'm not a networks expert so please if anyone can fix some of my assumptions if there is something wrong:
For explanation I just use unreal stuff(reqTimestamp,...), but the concept is valid(I hope):
The device signed the request with a timestamp and a timeout, for example, reqTimestamp=22:16, reqTimeout=22:17, my device is connected throught my wifi, so when the modem connected to my computer, a basic check on my computer or internally the modem, such as: if(reqTimeout > timeNow) reject, could prevent the request from even leave my network so Firebase issue this generic error regarding network problem.
I was getting this same error for a react-native project running using expo on an android device emulator(on windows).
I know this will sound weird but in my case I was getting this error when using internet from my phone's hotspot. When I switched to my normal wi-fi internet connection, the error went away.
Hope this helps.
I have the same error.
In my case it caused by more then one identifier for the same email in Firebase -> Authentication.
Do not know why I have more than one record for the same email, but after deleting all and login again. The problem is resolved.
I had the same issue. I connected to a VPN, the error went away.