Mongoose and multiple database in single node.js project

前端 未结 6 2373
难免孤独
难免孤独 2020-11-22 11:58

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 proble

6条回答
  •  我在风中等你
    2020-11-22 12:49

    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/
    

    In foo_db_connect.js

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

    In bar_db_connect.js

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

    In db_access.js files

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

    Now, you can access multiple databases with mongoose.

提交回复
热议问题