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

标签 node.js mongodb web-applications

我正在使用 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/

相关文章:

java - 启动画面 jnlp 不工作

c++ - 有没有办法用 cgicc 提取自定义请求 header

node.js - Socket.io 0.9 和 1.0 向所有房间成员广播

node.js - Sequelize::Limit and Order INSIDE 一个 Include[] 结构

c# - 使用 NoRM 驱动程序的 MongoDb 中的多态性问题

mongodb - 当按数组中的子字段排序时,sort() 在 MongoDB 中做了什么?

python - 如何使用 insert_many 安全地忽略重复键错误

javascript - 在 JavaScript 中解析二进制数据

linux - Node.js + peerjs 不使用 ssl

node.js - Flutter + socket.io 连接