No primary server available when failover happens: MongoDB, Node.js, Mongoose - node.js

I am currently facing an issue when failover happens in mongodb replica set. The app fails to reconnect to the newly elected primary server and fails to perform all subsequent write operations.
Restarting app reconnects successfully.
The failover happens instantly and a new primary is elected. However, the app fails to connect to the new primary.
mongodb version: 3.2.6
mongoose version: 4.3.4
node.js version:0.10.26

I was also facing a similar problem then I just changed
mongoose.connect(db)
to
mongoose.connect(db, {useNewUrlParser: true})
and now it is working fine

I have a primary, secondary and an arbiter set up running in three different nodes. This is how I connect using mongoose and the failover works perfectly fine.
mongoose.connect('mongodb://user:pwd#a.com:27017,b.com:27017,c.com:27017/dbName');
So, everything expect mongodb:// are variables.

I had this problem but it turned out to be that I was trying to access from a non-whitelisted IP.

mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
use like this, it will work fine.

Related

Can't connect to mongodb container when i add path to a database

I’m running mongoDB as a docker container locally, and I initiate a database creation when starting the container. But I can’t seem to connect to the database from my nodejs application when I add path to the dB. For example i can connect when I use “mongoDB://admin:password#localhost:27017” but not when I use “mongoDB://admin:password#localhost:27017/myDB”.
I'm running the container with docker-compose. Also when I log the output of running the mongo container I see a failure message that says:
"result":"UserNotFound: Could not find user \"admin\" for db \"journalDB\""}}
JournalDB is the name of the db i want to connect to, and i want to be able to connect to it from my nodejs application like so:
mongoose
.connect("mongoDB://admin:password#localhost:27017/journalDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
I have read the answer to a similar question here and this documentation , but I feel they have only explained the possible problem, but have not helped me fix it.
I would really appreciate it if there's a straightforward solution.
Maybe try
.connect("mongoDB://admin:password#localhost:27017/journalDB?authSource=admin" ...

Mongoose connection to replica set not working

I am running my own MongoDb Replica Set on Kubernetes.
It has 3 members, I exposed them all via NodePort.
I can connect to it via shell:
(feel free to connect, it's an empty, isolated example that will be destroyed)
mongo mongodb://stackoverflow:practice#134.122.99.184:31064,134.122.99.184:31086,134.122.99.184:32754/thirty3?authSource=admin
However, I cannot connect to it via mongoose 5.11.12 using the same connection string.
It only works until mongoose 4.5.8
mongoose.connect("mongodb://stackoverflow:practice#134.122.99.184:31064,134.122.99.184:31086,134.122.99.184:32754/thirty3?authSource=admin&replicaSet=thirty3&?retryWrites=true&w=majority",
{
useNewUrlParser: true,
poolSize: 5,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000, // Timeout after 5s instead of 30s
})
I tried tons of configurations, gssapiServiceName=mongodb, replicaSetName=thirty3 (I checked the replica set name by running rs.conf() ) and many more other configurations.
My question is - is there something wrong with mongoose handling these types of communications?
I have found similar issues that indicate downgrading as a solution, but downgrading is not ideal unless impossible to fix it normally.
Please try the code samples above, the database is open for connections with the credentials exposed.
This configuration works for me in Local MongoDB with a replica set.
await mongoose.connect("mongodb://localhost:27017/movieku", { family: 4 })
Source: https://docs.w3cub.com/mongoose/connections

Why I am able to access mongodb without running local mongo server?

I am beginning with server side programming by following a online course. As per my understanding, we use mongoose.connect(url) to connect to mongodb where url can be localhost url on which mongodb server is running.
But recently I forgot to run the local mongodb server using mongod. When I ran my node app with following code, it worked just fine :
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost:27017/TodoApp');
const {Todo} = require('./../server/models/todos');
const {ObjectID} = require('mongodb');
Todo.remove({}).then((result)=>{
console.log(result);
});
It worked fine with no error even though mongodb server was not running. When I checked the local database using Robo-3T tool, the documents were removed. I have verified this again.
I am unable to understand why my node app was able to connect to mongodb://localhost:27017/TodoApp even though mongodb server was not running on localhost:27017. Also, why Robo-3T tool was able to connect to this localhost: 27017 if server was not running.
Thanks.
The mongodb server was already running. Looks like the server does not shuts down on closing the terminal. It still runs in background. We have to close it using Ctrl+C.
More info: mongodb doesn't stop when I close terminal
Thanks #Sergio Tulentsev.
The reason is simple, the process is running in the background. If you search for 'services' - (in windows), scroll down to check for MongoDb, you will see that the process is running (Started). If set to Automatic, it starts up even after every restart.
Another reason is MongoDB server runs as a service in the background. Even if you restart your computer, it may be running.
I recognized at my win 10, MongoDB server is automatically started. So, you don't need to run mongod on your local.
At win 10 you can check it by:
type services in the search box;
open Services window;
Find MongoDB Server in the list;
Check Startup Type.
Probably your startup type is Automatic, you can change MongoDB Server startup type here.
It occurs when you don't stop the server explicitly and close your terminal.The server is running in background.You can see that in your task manager as well. Press Ctrl+C to quit and it will stop your server.

Mongoose calls hangs

I haven't worked on my PC for few days.
Suddenly all the calls to mongo via mongoose hangs up, the callbacks are not called.
I checked that my call to .connect works, and that the connection state is 1 (connected).
I also made sure mongo service is running on localhost and the appropriate port 27017, and I can use the mongo console and query the db manually.
I also scanned the Internet for solutions but all I found was 'check that you're actually connected', and I verified that already.
Mongoose version 2.15.0, mongo version 2.4.9 and node js version is 4.4.2.
I fixed it.
Problem was duplicate references to the mongoose module.
I had a mongoose reference locally (which was connected), but my schema was present higher in the node_modules hierarchy, and it have used another mongoose instance which had no connection.
Once I removed the duplicate mongoose modules (npm uninstall mongoose one of them) it worked.
Above solutions didn't work for me so I fixed with following solution.
I had same issue where my db calls used to hang with no invocation to my callbacks or the promise resolution.
The problem was I used "createConnection()" to establish the connection with the db. But it didn't work perfectly.
Instead using "connect()" and "connection" imports worked.
Here is the sample code. Hope this helps.
import { connect, connection } from "mongoose";
const mongoUri = `mongodb://${my_mongo_host_&_port}`;
connect(mongoUri, {}); //to connect to my standalone db
//"connection" to listen to events
connection.on("connected", () => {
console.log("MongoDB connection established!", mongoUri);
});
I am working with "mongoose": "^6.6.1".

Correct Use of Mongoskin

I usually work with mongoskin because I like to be close to the database. Usually, I do a setup with a file like db.coffee, that contains just this:
mongo = require 'mongoskin'
# either local
module.exports = mongo.db 'mongodb://localhost/database'
# or remote
module.exports = mongo.db 'mongodb://<user>:<pass>#<host>:<port>/<db>?auto_reconnect=true'
Then I use it in my other sources:
db = require 'db'
users = db.collection 'users'
# Now use the collection in handlers and middleware
This seems to work perfectly fine when I am using a local mongo server, I've had an uptime for months and it never turned out to be a problem.
However, when I am using the remote second, I get problem if the server runs longer than just a few minutes - the connection to the mongodb seems lost, despite auto_reconnect. I guess this is because the localhost connection is never closed automatically.
However this led me to thinking if I am maybe using mongoskin in a wrong way, or if there's simply a bug with the auto_reconnect?
ensure mongoskin is using the 1.0.0 or higher driver

Resources