Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I read the quick start from the Mongoose website and I almost copy the code, but I cannot connect the MongoDB using Node.js.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
exports.test = function(req, res) {
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  console.log("h1");
  db.once('open', function callback () {
    console.log("h");
  res.render('test');

This is my code. The console only prints h1, not h. Where am I wrong?

When you call mongoose.connect, it will set up a connection with the database.

However, you attach the event listener for open at a much later point in time (when a request is being handled), meaning that the connection is probably already active and the open event has already been called (you just weren't yet listening for it).

You should rearrange your code so that the event handler is as close (in time) to the connect call as possible:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
exports.test = function(req,res) {
  res.render('test');

The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection.

Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection.

If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose. Hope this helps out someone!

Here's the code.

var mongoURI;
mongoose.connection.on("open", function(ref) {
  console.log("Connected to mongo server.");
  return start_up();
mongoose.connection.on("error", function(err) {
  console.log("Could not connect to mongo server!");
  return console.log(err);
mongoURI = "mongodb://localhost/dbanme";
config.MONGOOSE = mongoose.connect(mongoURI);
                This code is more reliable then the accepted answer, while the accepted answer explains more clearly.
– hankchiutw
                Mar 21, 2016 at 5:52
                This helped a lot. I was certain the problem was my connection string, because I always have trouble with that the first time I use a new database. This code gave me the confirmation of the problem I needed.
– Juan Marco
                Apr 7, 2018 at 1:45

Mongoose connection using Singleton Pattern

Mongoose Connection File - db.js

//Import the mongoose module
const mongoose = require('mongoose');
class Database { // Singleton
  connection = mongoose.connection;
  constructor() {
    try {
      this.connection
      .on('open', console.info.bind(console, 'Database connection: open'))
      .on('close', console.info.bind(console, 'Database connection: close'))
      .on('disconnected', console.info.bind(console, 'Database connection: disconnecting'))
      .on('disconnected', console.info.bind(console, 'Database connection: disconnected'))
      .on('reconnected', console.info.bind(console, 'Database connection: reconnected'))
      .on('fullsetup', console.info.bind(console, 'Database connection: fullsetup'))
      .on('all', console.info.bind(console, 'Database connection: all'))
      .on('error', console.error.bind(console, 'MongoDB connection: error:'));
    } catch (error) {
      console.error(error);
  async connect(username, password, dbname) {
    try {
      await mongoose.connect(
        `mongodb+srv://${username}:${password}@cluster0.2a7nn.mongodb.net/${dbname}?retryWrites=true&w=majority`,
          useNewUrlParser: true,
          useUnifiedTopology: true
    } catch (error) {
      console.error(error);
  async close() {
    try {
      await this.connection.close();
    } catch (error) {
      console.error(error);
module.exports = new Database();

call the connection from app.js

const express = require("express"); // Express Server Framework
const Database = require("./utils/db");
const app = express();
Database.connect("username", "password", "dbname");
module.exports = app;

Mongoose's default connection logic is deprecated as of 4.11.0. It is recommended to use the new connection logic:

  • useMongoClient option
  • native promise library
  • const defaultOptions = { // Use native promises (in driver) promiseLibrary: global.Promise, useMongoClient: true, // Write concern (Journal Acknowledged) w: 1, j: true function connect (mongoose, dbURI, options = {}) { // Merge options with defaults const driverOptions = Object.assign(defaultOptions, options); // Use Promise from options (mongoose) mongoose.Promise = driverOptions.promiseLibrary; // Connect mongoose.connect(dbURI, driverOptions); // If the Node process ends, close the Mongoose connection process.on('SIGINT', () => { mongoose.connection.close(() => { process.exit(0); return mongoose.connection;
    mongoose.connect(<connection string>);
    mongoose.Promise = global.Promise;
    mongoose.connection.on("error", error => {
        console.log('Problem connection to the database'+error);
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.