My MongoDB was working fine but at some point, I was facing issues to connect my express server with the DB. when I start the DB using mongod it shows me 2020-05-21T14:36:41.819+0600 I NETWORK [initandlisten] waiting for connections on port 27017 which seems like a normal "running" entry. Then I run my express server where I connect the DB like this:
...
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/db_name';
const connect = mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
connect.then(
(db) => {
console.log('Connected correctly to server');
},
(err) => {
console.log(err);
}
);
...
which log Connected correctly to server but when I see the mongod running shell then there still the message which showed that it still waiting for the connection. And the most surprising issue is I can perform database related work in my express server. when I check the document using mongo, I see they correctly added to the database. I can't understand then why mongod behave like this. here is the full log of the mongod shell.
Update:
I forgot to add one important piece of information which is whenever I start my MongoDB server using mongod, in the C:\data\db directory there generate a new mongod.lock file. I tried to delete it and restart my server but eventually it generates again.
Related
I am using NextJS to build an app. I am using MongoDB via mongoosejs to connect to my database hosted in mongoAtlas.
My database connection file looks like below
import mongoose from "mongoose";
const MONGO_URI =
process.env.NODE_ENV === "development"
? process.env.MONGO_URI_DEVELOPMENT
: process.env.MONGO_URI_PRODUCTION;
console.log(`Connecting to ${MONGO_URI}`);
const database_connection = async () => {
if (global.connection?.isConnected) {
console.log("reusing database connection")
return;
}
const database = await mongoose.connect(MONGO_URI, {
authSource: "admin",
useNewUrlParser: true
});
global.connection = { isConnected: database.connections[0].readyState }
console.log("new database connection created")
};
export default database_connection;
I have seen this MongoDB developer community thread and this GitHub thread.
The problem seems to happen only in dev mode(when you run yarn run dev). In the production version hosted on Vercel there seems to be no issue. I understand that in dev mode the server is restarted every time a change is saved so to cache a connection you need to use as global variable. As you can see above, I have done exactly that. The server even logs: reusing database connection, then in mongoAtlas it shows like 10 more connections opened.
How can I solve this issue or what am I doing wrong?
I am using mongoose to connect to a remote mongodb server as below; when running on my local machine it works fine; I can also shell into the db without any problem locally. But after I deployed my express api to a server running on a container in AWS ECS. I got: Server selection timed out after 30000 ms
process.env.MOCK_DB=mongodb://username:password#somedomain.com:37017/db_name?directConnection=true
connect(process.env.MOCK_DB, { autoIndex: false }, (err: any) => {
if (err) {
log('cannot connect to mongodb:', err.message);
} else {
isDBConnected = true;
log("Connected to mongodb!");
}
});
What do I need to config?
Please try connecting with time limit more than 30s.
Like this:
process.env.MOCK_DB=mongodb://username:password#somedomain.com:37017/db_name?directConnection=true&socketTimeoutMS=360000&connectTimeoutMS=360000
You can visit this link and find the appropriate solution for your error.
problem
I'm trying to connect to mongodb with nestjs(^8.2.3) and typeorm(^0.2.28)
In test environment, connecting to mongodb standalone server is working. For your information, node mongodb library version is ^3.6.2.
production sample code(nestjs server)
I referred the typeorm code to write mongodb options
import { TypeOrmModule } from '#nestjs/typeorm';
import { MongoConnectionOptions } from 'typeorm/driver/mongodb/MongoConnectionOptions';
export const configForOrmModule = TypeOrmModule.forRootAsync({
imports: [],
useFactory: async () => {
const mongodbConfig: MongoConnectionOptions = {
type: 'mongodb',
username,
// for replicaSet (production)
hostReplicaSet: 'server1.example.com:20723,server2.example.com:20723,server.example.com:20723',
replicaSet: 'replicaSetName'
port: Number(port),
password: encodeURIComponent(password),
database,
authSource,
synchronize: true,
useUnifiedTopology: true,
entities: [Something],
};
return mongodbConfig;
},
inject: [],
});
But in production environment, when nestjs server try to connect to mongodb replicaSet, the server get this server selection loop error message over and over again like below. Interesting thing was the domain that the server tried to connect was different from replicaSet hosts(ex. another-hostname not included in server1.example.com:20723,server2.example.com:20723,server.example.com:20723). (+ edited: the another hostname is actual physical server indicated by the dns(server.example.com))
[39m01/28/2022, 2:39:16 AM [31m ERROR[39m [38;5;3m[TypeOrmModule] [39m[31mUnable to connect to the database. Retrying (3)...[39m
MongoServerSelectionError: getaddrinfo ENOTFOUND <another-hostname>
at Timeout._onTimeout (/home/node/app/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
what I’ve tried but these not worked
remove useUnifiedTopology: true option
downgrade mongodb library version to 3.5.11 (I've read in mongodb community there are something bug with topology after 3.6 version)
use host option not the hostReplicaSet
if you need more information, please tell me. thank you for your helping.
It was kubernates DNS issue. The hostReplicaSet server1.example.com:20723,... is resolved to host1 (physical server name. without example.com) but, k8s doesn't know it. so connection was failed.
there are two options
update kubernates /etc/hosts setting to add host1 -> host1.example.com
or update mongodb hostname host1 -> host1.example.com
The initial connection to the database seems to authenticate fine with this:
mongoose.connect('mongodb://user:pass#localhost/traderdb/?authSource=admin', {
auth: {
authdb: "admin"
}
}, function(e) {
//other things
});
After that however, when I try to create a new session and authenticate the user everything crashes and in the mongo logs I can see that the application tried to authenticate with mongodb using the traderdb database and not the admin database, even though I have authSource set correctly and it connects fine the first time with the same URI.
This is where I initialize the session store. This is placed inside the callback of the mongoose.connect call.
app.use(session({
secret: 'secrettexthere',
saveUninitialized: true,
resave: true,
store: new MongoStore({
url: 'mongodb://user:pass#localhost/traderdb/?authSource=admin',
db: 'traderdb',
collection: 'sessions',
auto_reconnect: true
})
}));
Nothing fails on application startup, and the mongo logs confirm that a connection was successfully made and authenticated with the admin database. After that however, when I try to actually use the session store the application crashes with the error Error: Error setting TTL index on collection : sessions. And in the mongo server logs I can see that my application tried connecting and authenticating with traderdb instead of admin as the authentication source.
I've come across a node chat example on github, When I try to run it, I see the following error:
Error connecting to mongo perhaps it isn't running ?
I've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 and other dependencies. The example can be found here: https://github.com/gregstewart/chat.io
I can not determine whether if the example not really works or I didn't run it right. Please help.
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.
Check out the follwing code excerpts from chat.io.
main.js:
/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);
Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).
UserProvider.js:
UserProvider = function(host, port) {
this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
this.db.addListener('error', function(error) {
console.log('Error connecting to mongo -- perhaps it isn\'t running?');
});
this.db.open(function() {
});
};
Opening the connection to the server, printing out an error on failure (the error you mentioned above).
Consider reading up on the mongo-db docs concerning installation and setup here