Mongoose and multiple database in single node.js project

前端 未结 6 2292
难免孤独
难免孤独 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:22

    As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.

    var Mongoose = require('mongoose').Mongoose;
    
    var instance1 = new Mongoose();
    instance1.connect('foo');
    
    var instance2 = new Mongoose();
    instance2.connect('bar');
    

    This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.

提交回复
热议问题