将猫鼬作为函数的参数传递 [英] passing mongoose as an argument to a function
问题描述
我正在开发一个节点模块.我需要将 mongoose 传递到模块中,以获取三项内容( mongoose.connection , mongoose.connection.db , mongoose. mongo ).
I'm developing a node module. I need to pass the mongoose to my module to get three things (mongoose.connection, mongoose.connection.db, mongoose.mongo) out of it.
index.js (myModule-我开发的模块)
index.js (myModule - the module I developed)
function myModule(mongoose) {
var db = mongoose.connection;
var gfs = gridfsLockingStream(mongoose.connection.db, mongoose.mongo);
this.someFunction = function() {//some code here}
}
module.exports = myModule;
db.js (用户必须这样使用myModule)
db.js (A user must use myModule like this)
var mongoose = require('mongoose');
var myModule = require('myModule');
var dbUrl = 'mongodb://localhost:27017/gfsTestDB';
mongoose.connect(dbUrl);
var readyObj = new myModule(mongoose);
module.exports = readyObj; // so that the user can use this everywhere
然后,用户可以使用 readyObj 进行工作. 我的问题是 myModule 函数中只有 mongoose.connection 可用,并且出现此错误(gridfsLockingStreamn导致该错误):
Then the user can use readyObj to do his/her work. My problem is that only mongoose.connection is available in myModule function and I get this error(gridfsLockingStreamn cause the error):
错误:缺少db参数
Error: missing db argument
新网格(db,mongo)
new Grid(db, mongo)
我正在使用:
"mongodb": "3.0.4",
"mongoose": "4.11.6",
"gridfs-locking-stream": "1.1.1",
"gridfs-stream": "1.1.1",
一种解决方案(来自@GrégoryNEUT的想法)(但我认为这不是正确的方法):
One solution (idea from @GrégoryNEUT) (but I think it's not the correct way):
index.js 不变
db.js 使用 promise 和 mongoose事件处理程序
var mongoose = require('mongoose');
var myModule = require('myModule');
var dbUrl = 'mongodb://localhost:27017/gfsTestDB';
mongoose.connect(dbUrl);
module.exports = new Promise(function (resolve, reject) {
mongoose.connection.on('connected', function () {
var readyObj = new myModule(mongoose);
resolve(readyObj);
});
});
photoRouter.js (用户的文件之一-用户要使用 readyObj )
photoRouter.js (one of the user's files - the user want to use readyObj)
var readyObj = require('./db').then(function (readyObj) {
// then the user uses readyObj
}
代码可以改进吗?
推荐答案
您可以使用Promises.
You can use of Promises.
var mongoose = require('mongoose');
var myModule = require('myModule');
var dbUrl = 'mongodb://localhost:27017/gfsTestDB';
mongoose.connect(dbUrl)
.then(
// The connection is ready to use!
() => {
var readyObj = new myModule(mongoose);
// ...
},
// Handle the connection error
(err) => {
// ...
},
);
您可以使用回调
You can use of Callbacks
var mongoose = require('mongoose');
var myModule = require('myModule');
var dbUrl = 'mongodb://localhost:27017/gfsTestDB';
mongoose.connect(dbUrl, (err) => {
if (err) {
// Handle the error
// ...
return;
}
// We get successfully connected to the database
var readyObj = new myModule(mongoose);
// ...
});
这篇关于将猫鼬作为函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!