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

前端 未结 4 1297
抹茶落季
抹茶落季 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:04

    You want your connection to act like a singleton so as mentioned in the answer above it makes sense to do it outside of, and preferable before your routes:

    var compression = require('compression');
    var express  = require('express');
    var app      = express();
    var port     = process.env.PORT || 8080;
    var cookieParser = require('cookie-parser');
    var bodyParser   = require('body-parser');
    var session      = require('express-session');
    ...
    
    app.use(compression());
    // db
    var mongoose = require('mongoose');
    var configDB = require('./config/database.js');
    mongoose.connect(configDB.url); // connect to our database
    

    config/database.js:

    module.exports = {
    'url' : '@localhost:27017/dbname'
    };
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-02-10 00:17

    Its best practice to have your db connection in a separate module (db.js)

    var mongoose = require('mongoose')
    
    mongoose.connect('mongodb://localhost/dbname', function(){
        console.log('mongodb connected')
    })
    module.exports = mongoose
    

    Each model should have a separate module that takes in the db connection (post.js)

    var db = require('../db.js')
    var Post = db.model('Post', {
        username: {type: String, required: true},
        body: {type: String, required: true},
        date: { type: Date, required: true, default: Date.now }  
    })
    
    module.exports = Post
    

    Then whenever you need to use that data set just require it and make calls

    var Post = require('/models/post')
    Post.save()
    Post.find()
    
    0 讨论(0)
  • 2021-02-10 00:27

    This is an opinion based question I'd say. What I use for my app is

    app.get('/', function (req, res) {
    res.sendfile('index.html');
    });
    mongoose.connect('mongodb://localhost:27017/my_db'); 
    

    This way I create a connection once rather than on every HTTP request. Your way should work fine but it seems you will have to connect and disconnect the db to your app way too many times specially when the app is in development.

    0 讨论(0)
提交回复
热议问题