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

前端 未结 4 1298
抹茶落季
抹茶落季 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'
    };
    

提交回复
热议问题