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
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());

// parse application/x-www-form-urlencoded
// for easier testing with Postman or plain HTML forms
app.use(bodyParser.urlencoded({
  extended: false
}));

// parse application/json
app.use(bodyParser.json())

// Use morgan for http request debug
app.use(morgan('dev'));

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 },
  }));

  app.use(require('webpack-hot-middleware')(compiler));
}

// pass the passport middleware
app.use(passport.initialize());

// 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();
  res.json(users);
});

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

app.get('/users/userId', async (req, res) => {
  const user = await User
    .findById(req.params.userId)
    .populate('recipes');
    
  console.log('user from api', user);
  res.json(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__) {
    res.send(renderHtmlPage(store));
    return;
  }

  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) {
      res.status(500).send(error.message);
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (!renderProps) {
      res.sendStatus(404);
    } 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
      Promise.all(promises)
        .then(() => {
          const content = renderToString(
            <Provider store={store}>
              <RouterContext {...renderProps} />
            </Provider>,
          );

          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);

mongoose.connect(config.dbUri);

const db = mongoose.connection;

mongoose.Promise = global.Promise;

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

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

if (config.port) {
  app.listen(config.port, config.host, (err) => {
    if (err) console.error(`==> ๐Ÿ˜ญ  OMG!!! ${err}`);

    console.info(chalk.green(`==> ๐ŸŒŽ  Listening at http://${config.host}:${config.port}`));
    // Open Chrome
    require('../tools/openBrowser').default(config.port);
  });
} else {
  console.error(chalk.red('==> ๐Ÿ˜ญ  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...