jeudi 26 mai 2016

Native MongoDB Driver Node.js - should we store collections?

I haven't been able to find any documents outlining if it's a bad / good idea to keep a reference to a collection so that it can be re-used after the db connection has been established.

for instance, in our database.ts which is called during our server start-up. It will grab the collections and store it for use in the module which can then be references throughout the project.

example of storing the collection

/*database.ts*/
//module to keep 1 connection alive and allow us to have 1 instance of our collections.
import {MongoClient, Db, Collection } from 'mongodb';

let uri: string = 'connection_string';

export let db: Db;

export let usrCollection: Collection;

export let bookCollection: Collection;

export function initDb(cb: any) {
  MongoClient.connect(uri, function(err, database) {
    //handle err        

    db = database;
    cb(); //returns now since db is assigned.
  });
}

export function initCollections() {
  usrCollection = db.collection('users'); //non-async
  bookCollection = db.collection('book'); //non-async
}

  
/*app.ts*/
  
//in our express app when it start up
import {db, initCollections, initDb} from './database';

initDb(function() {
  //this will hold up our server from starting BUT 
  //there is no reason to make it async.
  initCollections();
});

what are some of the short coming of this pattern/build? what can I improve and what should I avoid for performance hits specificially with managing the collections.would this pattern keep my source code bug free or easy to find the bugs and extensible for the future? or is there even a better pattern - please no ext library aside from the native mongodb driver for node.js solutions, such as mongoose.

Aucun commentaire:

Enregistrer un commentaire