What is the best practice to connect/disconnect to a database?

前端 未结 4 1286
抹茶落季
抹茶落季 2021-02-09 23:37

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

4条回答
  •  伪装坚强ぢ
    2021-02-10 00:16

    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;
    

提交回复
热议问题