Node js can't connect to my database using mongoose - node.js

I am trying to use use hyper terminal to connect to my mongodb database (created with mongoose) and when I use node app.js to try to connect to the database using hyper terminal, my terminal just freezes and return no response until I press ctrl c to exit and return to the previous line.
My mongoose code looks like the following:
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB');
Please note. I have already connected to the mongodb server by using mongodin the terminal and I have also cd to the directory of my folder where the app.js is located on my pc before running the node app.js on the terminal
screenshort of my terminal hyerterminal code screen
Please I need your help. Thank you

I believe that your terminal is NOT frozen, it is just that there is no console output in your code. You are connecting to Mongoose and then doing nothing after that.
Here are some suggestions,
You can use a callback to check if the connection is connected,
mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB').then(
() => {
console.log("Connected to DB!");
},
err => {
console.log(err);
}
);
Add a few event handlers to check if your connection is working,
mongoose.connection.on('open', function(){
console.log("Connection to Mongo DB is open!");
});
If you want to check for errors during "connect", you can chain an error handler in catch block.
mongoose.connect('mongodb://localhost:27017/test').
catch(error => console.log(error));
If you want to use Async/Await for the same error handling, then follow the below.
(async () => {
try {
await mongoose.connect('mongodb://localhost:27017/test');
console.log("Successfully connected to Mongo DB");
} catch (error) {
console.log(error);
}
})();
If you want to catch errors happening after the connection is connected to Mongo DB,
mongoose.connection.on('error', err => {
console.log(error);
});

Related

Mongoose connection printing out both console.log when mongo server not running

I have a mongoose connection to a mongodb server. When the server is running and it tries to connect it works fine and only prints out the single statement to the console. But when I haven't turned the mongo server on yet it prints both statements in the order they are in the code. I know this is not a huge error but would like to not have the health check show up as 'up' when the server is actually down.
Mongoose connection code:
mongoose.connect(config.db, {autoReconnect: true}, () => console.log('MongoDB has connected successfully.'));
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
The connect callback receives an error parameter you can check:
mongoose.connect(config.db, {autoReconnect: true}, (err) => {
if (!err) console.log('MongoDB has connected successfully.');
});
You can also separately handle the 'connect' event in the same way you're handling the 'error' event:
mongoose.connection.on('connect', function() {
console.error('MongoDB has connected successfully');
});

How to get node to exit when mongo connect fails

I'd like my Node JS app to exit immediately if it can't connect to Mongo. I'm using the mongodb node library.
I've reduced the code down to
const {MongoClient} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017');
If Mongo is not running, I get an UnhandledPromiseRejectionWarning with ECONNREFUSED, which I fully expect, but then the program hangs and never exits. This is with Node version 10.0.0.
Since the connection never succeeded I don't have a connection handle to close. I've tried various ways to catch the rejected promise, but I have been unsuccessful in getting the program to exit.
What do I need to do to shut down the MongoClient and make the program exit in this case?
Your application is remaining alive because it is trying to reconnect. You can try disabling the recconect:
MongoClient.connect('mongodb://localhost:27017', {
autoReconnect: false
}, (err, client) => {
if (client) client.close();
});
Or, you can terminate the process using process.exit(1) to kill the program.
const {
MongoClient
} = require('mongodb');
// Callback syntax
MongoClient.connect('mongodb://localhost:27017', (err, db) => {
if (err) process.exit(1);
});
// Promise syntax
MongoClient
.connect('mongodb://localhost:27017')
.catch(err => {
process.exit(1);
});
// Async/await syntax
(async function() {
let db;
try {
db = await MongoClient.connect('mongodb://localhost:27017');
} catch (err) {
process.exit(1);
}
}());

Mocha hangs after execution when connecting with Mongoose

Talk is cheap, show me the code
Linus Torvald
Doing integration tests with mocha and supertest. Here's the code
//app.js
mongoose.Promise = global.Promise;
mongoose.connect(config.mongoURL, error => {
if (error) {
throw error;
}
console.log('Connected to mongodb');
});
modules.export = app;
// test.js
it('returns 200', () => {
return supertest(app).get('/').expect(200);
});
Basically what happens is that the output "Connected to mongodb" logs after the tests are run (I have like 3 tests only, none use the db), and afterwards mocha hangs there and I have to Ctrl+C. I probably missed some configuration but I can't see it.
Needless to say, commenting the mongoose lines (mongoose.connect(...)) fixes it.
What am I missing?
You have to disconnect from the database after the tests are done. This can be done in the after function, for example.
after((done) => {
app.close(() => {
mongoose.connection.close(done);
});
});
If you don't disconnect you'll get the symptoms you are describing.
a more simplified answer
after((done) => {
mongoose.connection.close(done);
});

Node module; Mongod not returning promise at all?

I'm using mongod
module to start a MongoDB server for my node.js app.
I'm quite new to programming and after some googling I think it is the best I could come up with.
In mongod documentation, Mongod#open() returns a promise, which I believe I consume correctly.
However, my code never gets to the point where the client connects and I can't spot what I did wrong.
Here's my code:
const
Mongod = require('mongod'),
MongoClient = require('mongodb').MongoClient,
config = require('./config');
const
mongoURI = 'mongodb://localhost:27017/' + config.db.table_name,
server = new Mongod({
conf: config.db.path_to_cfg
});
const connectToDB = (uri) => {
return MongoClient.connect(uri);
};
//If mongod service is not running, create a new server and connect
console.log(server.isRunning); //Just to verify
if (!server.isRunning) {
console.log('dbConnect:: Starting MongoDB server...');
server.open()
.then(() => {
connectToDB(mongoURI)
.then((db) => {
console.log(db)
})
.catch((err) => {
console.log('Error: ' + err)
})
})
} else {
connectToDB(mongoURI)
.then((db) => {
console.log(db)
})
.catch((err) => {
console.log('Error: ' + err)
})
}
dbConnect:: Starting MongoDB server... logs in the console, the server runs successfully, since I can connect from windows CLI and query the database, but .then() is not executed and db is not logged.
I have tested the else block it is working as it should, (which also means my config module is correct) logging the db object when I have previously started the server from CLI.

not able to detect mongodb shutdown

My code:
db = mongoose.connect(
config[MONGO_HOST_CONF],
config[MONGO_ACCOUNTS_DB_CONF],
config[MONGO_PORT_CONF]
}
);
db.connection.on('opening', function() {
console.log("connecting");
});
db.connection.on('open', function() {
console.log("connected");
});
db.connection.on('error', function() {
console.log("disconnected");
});
db.connection.on('close', function() {
console.log("disconnected");
});
When I start my webserver which then opens a connection to mongodb, I can see "connected" in logs.
But when I do a mongodb stop, I dont see "disconnected" in logs. Neither do I see "connecting".
I am trying to detect if for some reason mongodb went down. Then reconnect before bailing out.
What is wrong above?
opening isn't an event that is sent by Mongoose, try connecting instead.
Also, close is an event that will be called when the client is closing the connection; in the situation where the server has stopped (or crashed), it isn't sent. Try using the disconnected event for that.

Resources