Node.js中的Mongodb集合对象缓存 [英] Mongodb collection object caching in Node.js

查看:77
本文介绍了Node.js中的Mongodb集合对象缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Node.js中为MongoDB数据库实现RESTful(ish)接口.根据 docs ,基本成语是像:

I'm trying to implement a RESTful(ish) interface to a MongoDB database in Node.js. According to the docs, the the basic idiom is something like:

var mongo = require('mongodb'),
  Server = mongo.Server,
  Db = mongo.Db;

var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('exampleDb', server);

db.open(function(err, db) {
     if(!err) {
        db.collection('test', function(err, collection) {
            // do stuff with collection
        });
     }
});

因此,基本的数据库访问涉及三个对象(服务器,数据库和集合).我的问题是其中哪些可以/应该在启动时加载并缓存在某个地方以供每个http请求重用,以及哪些/必须在每个请求中重新创建.我的假设是服务器和db对象可以长期存在,但是我对收集对象不太确定.

So there are three objects (server, db, and collection) involved in a basic DB access. My question is which of these can/should be loaded at startup and cached somewhere to be reused for every http request, and which must/should be recreated per request. My assumption is that it is okay for the server and db objects to be long lived, but I'm less sure about the collection object.

推荐答案

保存所有三项内容(服务器连接,数据库和集合),然后启动您的应用程序. 诸如猫鼬之类的MongoDB ODM会自己做,以防万一. 您可能需要使用 async 来避免将代码嵌套得太深.

Save all three things (server connection, database and collection) and kick off your app. ODMs for MongoDB like Mongoose do themselves, in case you're doubtful. You might want to use async to avoid nesting your code too deeply.

我个人使用 mongo-lite ,这让我可以做到var db = require('mongo-lite').connect('mongodb://localhost/exampleDb', ['test']); 之后,我可以摆弄我的收藏集db.test.这为我节省了很多样板.

Personally, I use mongo-lite which lets me do var db = require('mongo-lite').connect('mongodb://localhost/exampleDb', ['test']); After which I can fiddle with db.test, my collection. This saves me a lot of boilerplate.

这篇关于Node.js中的Mongodb集合对象缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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