简体   繁体   中英

Exporting a mongoose database module

I need to export my mongoose database module, so I could use my defined models from every module in my program.

For example, my database.js module looks something like that:

var mongoose = require('mongoose'),
    db = mongoose.createConnection('mongodb://localhost/newdb'),
    Schema = mongoose.Schema;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
    console.log("Connected to database newdb");

    var dynamicUserItemSchema = new mongoose.Schema({
      userID: Number,
      rank:  Number,
    });

    var staticUserItemSchema = new mongoose.Schema({
        _id: Schema.Types.Mixed,
        type: Schema.Types.Mixed,
    });

    var DynamicUserItem = db.model('DynamicUserItem', dynamicUserItemSchema);
    var StaticUserItem = db.model('StaticUserItem', staticUserItemSchema);

});

I want to be able adding var db = require('../my_modules/database'); to any other module my program - so I will be able to use the models like that:

db.DynamicUserItem.find(); or item = new db.DynamicUserItem({});

Is it possible doing that using "exports" or "module exports" ? Thanks.

I usually don't use the error and open events and follow the example from mongoosejs to create a connection to my db. Using the example you could do the following.

db.js

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');

var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);

module.exports = Cat; // this is what you want

and then in your app.js you can do something like

var Cat = require('db');

var peter = new Cat();

Hope that helps!

You can use exports to define a module that can be required elsewhere:

./models/list.js

var ListSchema = new Schema({
    name                : { type: String, required: true, trim: true }
    , description   : { type: String, trim: true }
});

module.exports = db.model('List', ListSchema);

./routes/list.js

var list = module.exports = {};

var List = require('../models/list');

list.get = function(req, res){
        List.find({ user: user._id }).exec(function(err, lists){
            res.render('lists', {
                lists: lists,
            });
        });
    });
};

./app.js

app.get('lists', routes.lists.get);

If you are using express, then I would put the models in the app.settings. You can do something like this at config time:

app.configure(function() {
  app.set('db', {
      'main'     : db
    , 'users'    : db.model('User')
  })
})

You would then be able to use the models like req.app.settings.db.users , or you can create a way to get the db var in the file you want in other ways.

This answer is not a complete example, but take a look at my starter project that sets up express and mongoose in a relative easy to use way: https://github.com/mathrawka/node-express-starter

As an adding to accepted answer, if you want to export multiple modules you can do:

In db.js:

var my_schemas = {'Cat' : Cat, 'Dog': Dog};
module.exports = my_schemas;

Then in the app.js:

var schemas = require('db');
var Cat = schemas.Cat;
var Dog = schemas.Dog;
Cat.find({}).exec({...});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM