簡體   English   中英

連接/斷開數據庫的最佳做法是什么?

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

我想知道如何在 MEAN 堆棧應用程序中連接到數據庫。 特別是,什么時候應該創建到數據庫的連接以及什么時候應該銷毀到數據庫的連接。 我應該在每個新的 HTTP 請求上創建和銷毀連接,還是應該存儲曾經創建的連接並盡可能長時間地將其用於任何后續請求。 我使用 Mongoose 作為建模工具。

這是一個例子。 這是我的帶有路由/indexroutes.js文件。 對該路由的請求應該從 MongoDb 數據庫中獲取一些日期。 我現在如何連接和斷開與數據庫的連接,這讓我很困擾。 是的,我完全按照 Mongoose 文檔中所寫的方式連接和斷開數據庫,但這是在嚴肅的生產環境中執行此操作的正確方法嗎?

var express = require('express');
var router = express.Router();

var config = require('./db-config');

// I create a Mongoose instance as a module object,
// as opposite to create it in every request handler function below.
var mongoose = require('mongoose');

var productSchema = require('../db/productSchema'); // model schema is also a module-wide object

// And here is a request handler function.
// It is called on every request as a brand new.
// I create and destroy a database connection inside this request handler
router.get('/index', function(req, res, next) {

    // I connect to a database on every request.
    // Do I need to do it here in a request handler?
    // May I do it outside of this request handler on a module-wide level?
    mongoose.connect('mongodb://my_database');

    // I create a new connection here in a request handler.
    // So it lives only during this request handler run.
    // Is this the right way? May I do it outside of this request handler 
    // on a module-wide level and somehow keep this connection and use it 
    // in every subsequent requests to this or any other route in the app?
    var db = mongoose.connection;

    db.on('connecting', function() {
        console.log('connecting');
    });

    db.on('connected', function() {
        console.log('connected');
    });

    db.on('open', function() {
        console.log('open');
    });

    db.on('error', console.error.bind(console, 'connection error'));

    db.once('open', function(cb) {
        var Product = mongoose.model('Product', productSchema);
        Product.find({category: "books"}, function(err, prods) {
            if (err) return console.error(err);

            // I close a connection here in a callback. 
            // As soon as successfully fetched the data. 
            // Do I need to close it after every request? 
            // What is the right place and time to do it? 
            db.close(disconnect);
            res.json(prods);
        });
    });
})

找到了一些很好的答案:

https://softwareengineering.stackexchange.com/questions/142065/creating-database-connections-do-it-once-or-for-each-query

.NET 中管理數據庫連接的最佳實踐是什么?

將數據庫連接放在單獨的模塊中的最佳實踐(db.js)

var mongoose = require('mongoose')

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

每個模型都應該有一個單獨的模塊,它接受數據庫連接(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

然后,只要您需要使用該數據集,只需要它並進行調用

var Post = require('/models/post')
Post.save()
Post.find()

這是一個基於意見的問題我會說。 我用於我的應用程序的是

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

這樣我就可以創建一次連接而不是每個HTTP請求。 你的方式應該工作正常,但似乎你必須連接和斷開數據庫與你的應用程序的方式太多次特別是當應用程序在開發中。

你希望你的連接像單身一樣行動,正如上面的答案中所提到的那樣,在你的路線之外做這件事是有意義的,並且更可取:

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

配置/ database.js:

module.exports = {
'url' : '@localhost:27017/dbname'
};

這是我的解決方案:

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

您應首先檢查連接成功與否的天氣,然后才能收聽某個端口。 這是我的app.js文件,其中加載了所有路由,因此您不必在所有文件中調用db連接。 您有一個配置文件,其中所有配置都已完成。 您的路由器文件user-routes.js看起來與此類似:

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;
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log("connected to DB!").catch((error) => console.log(error));]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM