导出mongoose数据库模块 [英] Exporting a mongoose database module

查看:96
本文介绍了导出mongoose数据库模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,我的database.js模块看起来类似的东西:

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

});

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

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(); item = new db.DynamicUserItem({});

是否有可能使用出口或模块出口来做到这一点?谢谢。

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

推荐答案

我通常不使用错误打开事件并按照 mongoosejs 中的示例创建与我的连接D b。使用该示例,您可以执行以下操作。

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

然后在你的app.js中你可以做类似

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

var Cat = require('db');

var peter = new Cat();

希望有所帮助!

这篇关于导出mongoose数据库模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆