Mongoose和多个数据库在单个node.js项目中 [英] Mongoose and multiple database in single node.js project

查看:100
本文介绍了Mongoose和多个数据库在单个node.js项目中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个包含子项目的Node.js项目。一个子项目将有一个Mongodb数据库,Mongoose将用于包装和查询db。但是问题是

I'm doing a Node.js project that contains sub projects. One sub project will have one Mongodb database and Mongoose will be use for wrapping and querying db. But the problem is


  • Mongoose不允许在单个mongoose实例中使用多个数据库,因为模型是在一个连接上构建的。 li>
  • 要使用多个mongoose实例,Node.js不允许多个模块实例,因为它在require()中有缓存系统。我知道在Node.js中禁用模块缓存,但我认为这不是好的解决方案,因为它只需要mongoose。

  • Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.
  • To use multiple mongoose instances, Node.js doesn't allow multiple module instances as it has caching system in require(). I know disable module caching in Node.js but I think it is not the good solution as it is only need for mongoose.

我尝试在mongoose中使用createConnection()和openSet(),但它不是解决方案。

I've tried to use createConnection() and openSet() in mongoose, but it was not the solution.

我试图深度复制mongoose实例( http:// blog。 imaginea.com/deep-copy-in-javascript/ )将新的mongoose实例传递到子项目,但它抛出RangeError:最大调用堆栈大小超过。

I've tried to deep copy the mongoose instance( http://blog.imaginea.com/deep-copy-in-javascript/ ) to pass new mongoose instances to the sub project, but it throwing "RangeError: Maximum call stack size exceeded".

我想知道有没有使用mongoose多个数据库或任何解决方法这个问题?因为我认为猫鼬是相当容易和快速。或者任何其他模块作为建议?

I want to know is there anyways to use multiple database with mongoose or any workaround for this problem? Because I think mongoose is quite easy and fast. Or any other modules as recommendations?

推荐答案

你可以做的一件事是,你可能有每个项目的子文件夹。所以,安装mongoose在那个子文件夹和require()mongoose从自己的文件夹在每个子应用程序。不是从项目根或从全局。所以一个子项目,一个mongoose安装和一个mongoose实例。

One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance.

-app_root/
--foo_app/
---db_access.js
---foo_db_connect.js
---node_modules/
----mongoose/
--bar_app/
---db_access.js
---bar_db_connect.js
---node_modules/
----mongoose/

在foo_db_connect.js

In foo_db_connect.js

var mongoose = require('./node_modules/mongoose');
mongoose.connect('mongodb://localhost/foo_db');
module.exports = exports = mongoose;

在bar_db_connect.js

In bar_db_connect.js

var mongoose = require('./node_modules/mongoose');
mongoose.connect('mongodb://localhost/bar_db');
module.exports = exports = mongoose;

在db_access.js文件中

In db_access.js files

var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app

现在,您可以使用mongoose访问多个数据库。

Now, you can access multiple databases with mongoose.

这篇关于Mongoose和多个数据库在单个node.js项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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