在连接回调之外访问db.collection

时间:2017-03-24 16:06:58

标签: node.js mongodb

如何使用对连接数据库的特定集合的引用来创建 var / object / module

如何创建模块以将引用导出到要在别处使用的特定集合:

模块connect-to-db.js

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://<user>:<password>@..shard..mongodb.net:<port>/<collection>?ssl=true&replicaSet=..shard..&authSource=admin';

// This part works
MongoClient.connect(url, function(err, db) {
   assert.equal(null, err);
   console.log('Connected to external MongoDB server');
   // db.close(); // not called to keep connection open

   // How do I return db to the outside of this callback's scope 
   //   to exports.user?  
});

// This is the part that's not working
// How do I access db.collection('users').find() from outside this module
module.exports.users = MongoClient;
// this should return a reference to db.collection('users') in exports.users

// where should I return 

然后可以从任何地方查询/写入该集合(使用 dBconnection.users ,如下所示):

主App server.js

var express = require('express');
var app     = express();
var dBconnection = require('./connect-to-db');
// is dBconnection is a reference to MongoClient.connection ?
// is dBconnection.users a reference to db.collection('users') ?

app.get('/db', function(req, res){

    // From here does not work
    records = dBconnection.users.find();
    // runtime error: cannot use .find() of undefined 
    // OR runtime error: find() is not a function of users 

    // Testing the query
    res.setHeader('Content-Type', 'text/plain');
    res.write('Attempting to display records\n');
    res.end(JSON.stringify(records, null, 2));
});

app.listen(3000, function () {
    console.log('Listening at port 3000')
});

最后我想让模块保持连接(即使被删除,可能会向导出添加.status属性以检查状态),以便我可以随时在server.js /其他模块/其他地方访问它路线/意见

1 个答案:

答案 0 :(得分:0)

Node中的模块无法导出任何立即可用的内容,因为节点模块导出且require()函数是同步的。 (有关详细信息,请参阅此答案:javascript - Why is there a spec for sync and async modules?

但是,您可以导出的内容是您需要的其他需求模块的承诺,例如db.collection('users')

例如,您可以执行以下操作:

module.exports.users = new Promise((resolve, reject) => {
    someAsyncFunction((err, data) => {
        if (err) return reject(err);
        resolve(data);
    });
});

然后其他模块就可以像:

一样使用它
require('./the/module').users.then(users => {
  // use the users
});

async个函数内部:

let users = await require('./the/module').users;
// use the users

但是,当您需要模块时,您将无法直接导出不可用的值。