Node.js和MongoDB,重用数据库对象 [英] Node.js and MongoDB, reusing the DB object

查看:94
本文介绍了Node.js和MongoDB,重用数据库对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js和MongoDB的新手,但是我设法将SO和mongo文档中的某些部分放在一起.

I'm new to both Node.js and MongoDB, but I've managed to put some parts together from SO and the documentation for mongo.

Mongo文档给出了示例:

Mongo documentetion gives the example:

// Retrieve
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});

如果我只需要在一个位置的一个功能中使用DB,那看起来还不错.在SO上进行搜索和阅读表明,我不应该每次都打开一个新连接,而应该使用一个池并重用我第一次获得的数据库对象.这个答案在SO上很丰富,但是我不确定如何首先获得DB对象,然后再如何使用它.

Which looks fine if I only need to use the DB in one function at one place. Searching and reading on SO has shown me that I should not open a new connection each time, but rather use a pool and reuse the database object I get the first time. This answer is abundant on SO, but I'm not sure how to even get the DB object in the first place, and then how to reuse it.

说我的App.js中有上面的Node.js代码,然后我有不同的路由,需要在db上运行不同的操作,例如:

Say I have the Node.js code above in my App.js, and I then have differnt routes that need to run different operations on the db like:

app.post('/employee', function(req, res){
    //Put req.name in database
});


app.post('/car', function(req, res){
    //Put req.car in database
});

我该如何将这两个片段组合成有用的东西?

How would I go about to put these two snippets together into something useful?

我在 Node.js重用MongoDB参考中发现了类似的问题,但是的外观( http://mongodb.github.io /node-mongodb-native/driver-articles/mongoclient.html ),看起来我应该使用MongoClient而不是db().而且我也不确定它是否可以解决我的问题...

I found a similar question in Node.js reuse MongoDB reference , but from the looks of this ( http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html ) it looks like I should use MongoClient rather than db(). And I'm not sure it solves my problem either...

推荐答案

您总是可以编写一个模块来初始化数据库连接,并使它们在整个程序中都可访问.例如:

You could always write a module which initializes your database connections, and makes them accessible throughout your program. For example:

mongo.js

var mongodb = require('mongodb');

module.exports.init = function (callback) {
  var server = new mongodb.Server("127.0.0.1", 27017, {});
  new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
    //export the client and maybe some collections as a shortcut
    module.exports.client = client;
    module.exports.myCollection = new mongodb.Collection(client, 'myCollection');
    callback(error);
  });
};

app.js

var mongo = require('./mongo.js');

//setup express...

//initialize the db connection
mongo.init(function (error) {
    if (error)
        throw error;

    app.listen(80); //database is initialized, ready to listen for connections
});

randomFile.js

randomFile.js

var mongo = require('./mongo.js');

module.exports.doInsert = function () {
  //use the collection object exported by mongo.js
  mongo.myCollection.insert({test: 'obj'}, {safe:true}, function(err, objects) {
    if (err)
        console.warn(err.message);
  });
};

我知道人们谈论池化,但是当我对池化mongo连接与针对所有请求的单个连接进行基准测试时,单个连接实际上执行得更好.当然,这是大约一年前的事,但是我怀疑基本概念已经改变.所有请求都是异步的,因此发出并发请求并不需要多个连接.

I know people talk about pooling, but when I did benchmarking of pooling mongo connections vs. a single connection for all requests, the single connection actually performed better. Granted, this was about a year ago, but I doubt that basic concept has changed. All the requests are asynchronous, so it's not like multiple connections are necessary in order to make simultaneous requests.

就MongoClient而言,我认为这是他们鼓励的新语法.无论哪种方式,它本质上都是一个 client 对象,无论使用哪种样式,您都希望保留该对象并使其可访问.

As far as MongoClient, I guess that's the new syntax they're encouraging. Either way, it's essentially a client object that you want to keep and make accessible regardless of which style you use.

这篇关于Node.js和MongoDB,重用数据库对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆