Mongoose connection error: Error: connection timeout

Mongoose connection error: Error: connection timeout


I start express server, mongoose successfully connects to local database :sweat_smile:, and then after a while (in several minutes) mongoose resets connection crashing app :open_mouth:. I canโ€™t figure the issue out :scream:

This is server.js file

import React from 'react';
import Express from 'express';
import path from 'path';
import morgan from 'morgan';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import favicon from 'serve-favicon';
import bodyParser from "body-parser";
import chalk from 'chalk';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { createMemoryHistory, match, RouterContext } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import passport from 'passport';
import mongoose from 'mongoose';
import jwt from 'jsonwebtoken';

import createRoutes from '../src/routes';
import configureStore from '../src/redux/store';
import { createSelectLocationState } from '../src/util/helpers';
import renderHtmlPage from '../src/util/renderHtmlPage';
import config from '../src/config';

import authCheck from './middleware/authCheck';
import { devErrorHandler, prodErrorHandler } from './middleware/errorHandlers';

import User from './models/user';
import Recipe from './models/recipe';

const app = Express();

// Using helmet to secure Express with various HTTP headers
// Prevent HTTP parameter pollution.
// Compress all requests

// parse application/x-www-form-urlencoded
// for easier testing with Postman or plain HTML forms
  extended: false

// parse application/json

// Use morgan for http request debug

app.use(favicon(path.join(process.cwd(), './public/favicon.ico')));
app.use(Express.static(path.join(process.cwd(), './public')));

// Run express as webpack dev server
if (__DEV__) {
  const webpack = require('webpack');
  const webpackConfig = require('../tools/webpack/config.babel');

  const compiler = webpack(webpackConfig);

  app.use(require('webpack-dev-middleware')(compiler, {
    publicPath: webpackConfig.output.publicPath,
    noInfo: true,
    stats: { colors: true },


// pass the passport middleware

// load passport strategies
const localSignupStrategy = require('./passport/local-signup');
const localLoginStrategy = require('./passport/local-login');
passport.use('local-signup', localSignupStrategy);
passport.use('local-login', localLoginStrategy);

// pass the authorization checker middleware
app.use('/api', authCheck);

// routes
const authRoutes = require('./routes/auth');
const apiRoutes = require('./routes/api');

app.use('/auth', authRoutes);
app.use('/api', apiRoutes);

app.get('/users', async (req, res) => {
  const users = await User.find();

app.get('/recipes', async (req, res) => {
  const recipes = await Recipe.find();

app.get('/users/userId', async (req, res) => {
  const user = await User
  console.log('user from api', user);

// Register server-side rendering middleware
app.get('*', (req, res) => {
  if (__DEV__) webpackIsomorphicTools.refresh();

  const store = configureStore();

  // If __DISABLE_SSR__ = true, disable server side rendering
  if (__DISABLE_SSR__) {

  const memoryHistory = createMemoryHistory(req.url);
  const routes = createRoutes(store);
  const history = syncHistoryWithStore(memoryHistory, store, {
    selectLocationState: createSelectLocationState('routing'),

  // eslint-disable-next-line max-len
  match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if (error) {
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname +;
    } else if (!renderProps) {
    } else {
      // Dispatch the initial action of each container first
      const promises = renderProps.components
        .filter(component => component.fetchData)
        .map(component => component.fetchData(store.dispatch, renderProps.params));

      // Then render the routes
        .then(() => {
          const content = renderToString(
            <Provider store={store}>
              <RouterContext {...renderProps} />

          res.status(200).send(renderHtmlPage(store, content));
        .catch((err) => {
          console.error(`==> ๐Ÿ˜ญ  Rendering routes error: ${err}`);
        .catch((err) => {
          console.error(`==> ๐Ÿ˜ญ  Rendering routes error: ${err}`);

__DEV__ ? app.use(devErrorHandler) : app.use(prodErrorHandler);


const db = mongoose.connection;

mongoose.Promise = global.Promise;

db.on('error', (err) => {
  console.error(`Mongoose connection error: ${err}`);

db.once('open', () => {
  console.log('DB connected!');

if (config.port) {
  app.listen(config.port,, (err) => {
    if (err) console.error(`==> ๐Ÿ˜ญ  OMG!!! ${err}`);`==> ๐ŸŒŽ  Listening at http://${}:${config.port}`));
    // Open Chrome
} else {
  console.error('==> ๐Ÿ˜ญ  OMG!!! No PORT environment variable has been specified'));


Mongoose part looks fine.
What is the crash error?


Error: connection timeout


How can you tell from that error that mongoose caused the crash?
Anyway, your mongoose code looks ok. I donโ€™t think it causes the cras.


the error crashes app and nodemon tells it with this line

[nodemon] app crashed - waiting for file changes before starting...