简体   繁体   English

导出猫鼬数据库模块

[英]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: 例如,我的database.js模块看起来像这样:

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'); 我希望能够添加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({}); 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. 我通常不使用erroropen事件,而是按照mongoosejs的示例创建与我的数据库的连接。 Using the example you could do the following. 使用该示例,您可以执行以下操作。

db.js 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 然后在您的app.js中,您可以执行以下操作

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 ./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 ./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.js

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

If you are using express, then I would put the models in the app.settings. 如果您使用的是Express,那么我会将模型放入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. 然后,您将能够使用诸如req.app.settings.db.users之类的模型,或者您可以通过其他方式创建一种在所需文件中获取db var的方法。

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 这个答案不是一个完整的例子,但请看一下我的入门项目,该项目以相对易于使用的方式设置了express和mongoose: 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: 在db.js中:

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

Then in the app.js: 然后在app.js中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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