I\'d like to know how to work with connectivity to a database in MEAN stack application. In particular, when should I create a connection to a database and when should I destroy
This is my solution :
import express from 'express';
import mongoose from 'mongoose';
import { name } from '../package.json';
import * as localconfig from './local-config';
import debug from 'debug';
debug(name);
const app = express();
const port = process.env.PORT || 3000;
const mongoUrl = localconfig.credentials.MONGO_URL;
import usersRoutes from './routes/users/user-routes';
app.use('/v1/users', usersRoutes);
mongoose.connect(mongoUrl)
.then(() => {
debug('DB connection successful');
app.listen(port, '0.0.0.0', () => {
debug(`Running on port ${port}`);
});
})
.catch((err) => {
debug(err);
});
You should first check weather the connection is successful or not and only then listen to a certain port. This is my app.js
file where all the routes are loaded, so you do not have to call the db connection in all your files. You have a single config file where all the config is done. Your router file user-routes.js
will look something similar to this:
import express from 'express';
import User from '../models/user'
const router = express.Router();
router.get('/', (req, res, next) => {
User.find()
.then((response) => res.json(response))
.catch((err) => next(err));
});
module.exports = router;