【发布时间】:2018-03-21 14:29:14
【问题描述】:
我正在开发自己的节点模块以将其放在 npm 网站上。该节点模块与数据库有一些交互。我需要从用户接收三个值(dbName、server、port)并将它们设置在我的模块中,以便我可以连接到数据库。我首先想到的是这样的: 要求用户打开配置文件并更改代码(将值分配给三个变量):
var dbConf = {
server: '',
port: 0,
dbName: ''
};
但我认为这种做法是完全错误的。我尝试创建一个函数并要求用户首先使用三个参数(dbName、服务器、端口)调用该函数,该函数为我完成了工作。然后用户首先需要我的模块,然后调用函数,最后使用模块:
var myModule = require('myModule');
myModule.config('TestDB', 'localhost', 27017);
myModule.someMethod()...
但我不知道如何编写我的 index.js 文件来完成这项工作!我写了这样的东西:(index.js)
var config = function(dbName, server, port ) {
var dbConf = {
server: '',
port: 0,
dbName: ''
};
dbConf.server = server;
dbConf.port = port;
dbConf.dbName = dbName ;
return 'mongodb://' + dbConf.server + ':' + dbConf.port + '/' +
dbConf.dbName;
}
//connect to mongoDB local server
mongoose.connect(config);
module.exports = {
config: config,
mongoose: mongoose
};
但它没有用。我怎么能做这份工作?
更新: index.js:
function gridFS(dbName, server, port) {
var dbUrl = 'mongodb://' + server + ':' + port + '/' + dbName;
this.mongoose = mongoose.connect(dbUrl);
this.db = mongoose.connection;
this.gfs = gridfsLockingStream(this.mongoose.connection.db,
this.mongoose.mongo);
//if the connection goes through
this.db.on('open', function (err) {
if (err) throw err;
console.log("connected correctly to the server");
});
this.db.on('error', console.error.bind(console, 'connection error:'));
}
gridFS.prototype.putFile = function putFile(...) {};
gridFS.prototype.getFileById = function getFileById(id, callback) {
this.putFile(); //here is the problem
}
module.exports = gridFS;
【问题讨论】:
标签: node.js node-modules