Javascript 导出 mongoose 数据库模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13668547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:37:19  来源:igfitidea点击:

Exporting a mongoose database module

javascriptnode.jsmongodbexpressmongoose

提问by Daniel

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

我需要导出我的 mongoose 数据库模块,这样我就可以使用我程序中每个模块中定义的模型。

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');to any other module my program - so I will be able to use the models like that:

我希望能够将var db = require('../my_modules/database');我的程序添加到任何其他模块 - 所以我将能够使用这样的模型:

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

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

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

是否可以使用“导出”或“模块导出”来做到这一点?谢谢。

回答by zemirco

I usually don't use the errorand openevents and follow the example from mongoosejsto create a connection to my db. Using the example you could do the following.

我通常不使用erroropen事件,而是按照mongoosejs的示例创建到我的数据库的连接。使用示例,您可以执行以下操作。

db.js

数据库.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!

希望有帮助!

回答by chovy

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

回答by staackuser2

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

如果您使用的是 express,那么我会将模型放在 app.settings 中。您可以在配置时执行以下操作:

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

回答by aesede

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