嘿伙计们,所以我对创建模块非常陌生,我在从主应用程序访问我的mongodb连接池时遇到了一些麻烦。
这是模块:
// mongo-pool.js
// -------------
var assert = require('assert');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'connection_url';
var mongoPool = {
start: function() {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Successfully connected to mongo");
// Make the db object accessible here?
});
}
}
module.exports = mongoPool;
当我需要mongo-pool.js
并调用mongoPool.start()
时它表示它已成功连接到mongo,尽管db对象无法进行查询。这是主要的js文件:
var mongoPool = require('./mongo-pool.js');
var pool = mongoPool.start();
var collection = pool.db.collection('accounts');
collection.update(
{ _id: 'DiyNaiis' },
{ $push: { children: 'JULIAN' } }
)
变量池未定义。我似乎无法弄清楚为什么,我在模块中尝试return db
,似乎没有用。
感谢任何帮助,谢谢!
答案 0 :(得分:0)
我的一个伙伴帮我弄清楚问题是什么,这是任何人遇到它的解决方案。
我更新了我的mongo-pool.js
模块,并将db属性分配给自己:
var assert = require('assert');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'my_database_url';
var mongoPool = {
start: function() {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var self = this;
self.db = db;
// THESE ASSIGNMENTS
console.log("Successfully connected to mongo");
// Make the db object accessible here?
});
}
}
module.exports = mongoPool;
然后在我的main.js
文件中:
var mongoPool = require('./mongo-pool.js');
// Include My mongo global module
new mongoPool.start();
// Initialize the new MongoDB object globally
setTimeout(function() {
console.log(db);
}, 3000);
// Set a 3 second timeout before testing the db object...
// It will return undefined if it's called before the mongo connection is made
现在,db
对象可从模块全局使用。