passing mongoose as an argument to a function

2020-05-05 17:58发布

问题:

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 - 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 (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

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):

Error: missing db argument

new Grid(db, mongo)

I'm using :

"mongodb": "3.0.4",

"mongoose": "4.11.6",

"gridfs-locking-stream": "1.1.1",

"gridfs-stream": "1.1.1",

One solution (idea from @GrégoryNEUT) (but I think it's not the correct way):

index.js no changes

db.js using promise and mongoose event handler

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 (one of the user's files - the user want to use readyObj)

var readyObj = require('./db').then(function (readyObj) {
    // then the user uses readyObj
}

Can the code be improved?

回答1:

Looking at the documentation of mongoose connect


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);

      // ...
    });