gpt4 book ai didi

node.js - 在 Node.JS Web 应用程序中使用 mongoDB

转载 作者:可可西里 更新时间:2023-11-01 09:46:13 24 4
gpt4 key购买 nike

我正在使用 Node.JS 编写一些简单的网络应用程序,并希望使用 mongoDB 作为主要数据存储。
Node-mongodb-native 驱动程序需要进行链式调用,然后才能真正查询或存储数据(打开 DB 连接、验证、获取集合)。
在初始化应用程序时,哪里是进行此初始化的最佳位置 - 在每个请求处理程序中还是在全局范围内?

最佳答案

最好将 Mongo 初始化放在请求处理程序之外 - 否则它会为提供的每个页面重新连接:

var mongo = require('mongodb');

// our express (or any HTTP server)
var app = express.createServer();

// this variable will be used to hold the collection for use below
var mongoCollection = null;

// get the connection
var server = new mongo.Server('127.0.0.1', 27017, {auto_reconnect: true});

// get a handle on the database
var db = new Db('testdb', server);
db.open(function(error, databaseConnection){
databaseConnection.createCollection('testCollection', function(error, collection) {

if(!error){
mongoCollection = collection;
}

// now we have a connection - tell the express to start
app.listen(80);

});
});

app.use('/', function(req, res, next){
// here we can use the mongoCollection - it is already connected
// and will not-reconnect for each request (bad!)
})

关于node.js - 在 Node.JS Web 应用程序中使用 mongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11985658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com