连接/断开数据库的最佳实践是什么?

2024-02-21

我想知道如何在 MEAN 堆栈应用程序中连接到数据库。特别是,何时应创建与数据库的连接以及何时应销毁与数据库的连接。我应该在每个新的 HTTP 请求上创建和销毁连接,还是应该存储曾经创建的连接并尽可能长时间地将其用于任何后续请求。我使用 Mongoose 作为建模工具。

这是一个例子。 这是我的routes.js带有路线的文件/index。对此路由的请求应从 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 https://softwareengineering.stackexchange.com/questions/142065/creating-database-connections-do-it-once-or-for-each-query

在 .NET 中管理数据库连接的最佳实践是什么? https://stackoverflow.com/questions/3258788/what-are-best-practices-on-managing-database-connections-in-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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

连接/断开数据库的最佳实践是什么? 的相关文章

随机推荐