13

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.

5 Answers 5

33

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks zeMirco. so that says that every model is in a diffrent file ?
that depends on you. You can export multiple models from one file (for example exports.Cat = Cat and exports.Dog = Dog) or stick with one model per file. For the later I would use a global config file for the database connection params.
7

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

1 Comment

db - where is it defined? is it global?
2

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

2 Comments

I think this does not add any value over the standard node/commonjs module system and couples your code to express's configuration system for no reason. Just KISS with commonjs modules.
Yes, it couples it with express and makes it easier to access common things like mongoose models. For production applications, sometimes the simple methods are not resilient enough.
2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.