Daniel
Daniel

Reputation: 1582

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.

Upvotes: 12

Views: 66594

Answers (5)

Ujjawal Kumar
Ujjawal Kumar

Reputation: 286

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const PersonSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  passowrd: {
    type: String,
    required: true,
  },
  username: {
    type: String,
  },
  profilepic: {
    type: String,
    default:
      "https://media.istockphoto.com/id/1131164548/vector/avatar-5.jpg?s=612x612&w=0&k=20&c=CK49ShLJwDxE4kiroCR42kimTuuhvuo2FH5y_6aSgEo=",
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

// exporting our person schema
module.exports = Person = mongoose.model("myPerson", PersonSchema);

Upvotes: 0

aesede
aesede

Reputation: 5703

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({...});

Upvotes: 2

chovy
chovy

Reputation: 75774

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

Upvotes: 7

zemirco
zemirco

Reputation: 16395

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!

Upvotes: 33

staackuser2
staackuser2

Reputation: 12412

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

Upvotes: 2

Related Questions