【问题标题】:Connect multiple mongo db database in node js using mongoose使用 mongoose 在节点 js 中连接多个 mongo db 数据库
【发布时间】:2017-08-12 14:17:02
【问题描述】:

我在节点 js 中使用 mongoose 进行 mongo db 连接。谁能告诉我如何在节点 js 中连接多个数据库。另外请确保您自己尝试过该方法。谢谢。

编辑:我想动态连接到多个数据库。另外我不想要多个模型,我只有一个项目,而不是各种子项目。

【问题讨论】:

  • @JohnnyHK 我更新了我的问题。此外,提供给另一个问题的答案也不能满足我的需要。无论如何,谢谢。
  • 您需要为您的问题添加更多细节。显示您目前拥有的连接代码,说明您正在尝试做什么以及什么不起作用。
  • @Jalasem - 这个问题是指不同控制器中的 2 个数据库,我想在单个控制器中实现相同的。

标签: node.js mongodb mongoose database


【解决方案1】:

我相信你是从主入口点连接到 mongoDB 作为 index.js 或 server.js ,你正在启动路由器。像这样 `

    const mongoose = require('mongoose')
    // mongoose
    mongoose.connect("mongoDB url");
    const connection = mongoose.connection;
    connection.on('open',()=>{
        console.log(" database connected")
    })
    connection.on('error',()=>{
        console.log("error in connecting to database")
    })
    app.use(morgan('dev'));
    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());
    //middlewares`

以同样的方式,您也可以直接连接到不同的数据库模式。就像在我的用例中一样,我想将用户存储在不同的数据库中并在另一个数据库中发布。 在我的 app.js 中,我将作为正常连接(上图)连接到主数据库,对于用户模式,我将连接到我的用户数据库。像这样

    const mongoose = require('mongoose');
    const connection = mongoose.createConnection("mongo url ");
    const userSchema = mongoose.Schema({
       name: String,
       date_of_birth: Date
      })
    module.exports = mongoose.model('User', userSchema);

您也可以使用mongoose.connect() 代替mongoose.createConnection()

希望这对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 2016-12-14
    • 2020-02-01
    • 1970-01-01
    • 2015-09-27
    • 2018-08-09
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多