سؤال

For my NodeJS project, I want to make a simple module that will give me the DB handle to work with. I thought of something like this:

settings = module.exports.settings =
    db: 'test'
    clear_interval: -1
    host: '127.0.0.1'
    port: '27017'
    auto_reconnect: true

{Db, Connection, Server, Collection, BSON, ObjectID} = require 'mongodb'

db = new Db settings.db, new Server settings.host, settings.port, { auto_reconnect: settings.auto_reconnect }
db.open ->
    module.exports.db = db

But is this really safe? Or is there an other way to make sure module.exports.db is properly set when the module is loaded?

EDIT Accidentally hit enter before I was done typing.

هل كانت مفيدة؟

المحلول

That won't work.

module.exports.db is set after the module has been required.

What you should do instead is something like

module.exports.DB = function (cb) {
  getDbAsync(cb);
}

Force your api to be asynchronous

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top