@@ -457,30 +457,10 @@ module.exports = userSchema;
457457// module.exports = mongoose.model('User', userSchema);
458458```
459459
460- If you use the export schema pattern, you still need to create models
461- somewhere. There are two common patterns. First is to export a connection
462- and register the models on the connection in the file:
463-
464- ``` javascript
465- // connections/fast.js
466- const mongoose = require (' mongoose' );
467-
468- const conn = mongoose .createConnection (process .env .MONGODB_URI );
469- conn .model (' User' , require (' ../schemas/user' ));
470-
471- module .exports = conn;
472-
473- // connections/slow.js
474- const mongoose = require (' mongoose' );
475-
476- const conn = mongoose .createConnection (process .env .MONGODB_URI );
477- conn .model (' User' , require (' ../schemas/user' ));
478- conn .model (' PageView' , require (' ../schemas/pageView' ));
479-
480- module .exports = conn;
481- ```
482-
483- Another alternative is to register connections with a dependency injector
460+ If you use the export schema pattern, you still need to create models somewhere.
461+ There are two common patterns.
462+ The first is to create a function that instantiates a new connection and registers all models on that connection.
463+ With this pattern, you may also register connections with a dependency injector
484464or another [ inversion of control (IOC) pattern] ( https://thecodebarbarian.com/using-ramda-as-a-dependency-injector ) .
485465
486466``` javascript
@@ -496,6 +476,23 @@ module.exports = function connectionFactory() {
496476};
497477```
498478
479+ Exporting a function that creates a new connection is the most flexible pattern.
480+ However, that pattern can make it tricky to get access to your connection from your route handlers or wherever your business logic is.
481+ An alternative pattern is to export a connection and register the models on the connection in the file's top-level scope as follows.
482+
483+ ``` javascript
484+ // connections/index.js
485+ const mongoose = require (' mongoose' );
486+
487+ const conn = mongoose .createConnection (process .env .MONGODB_URI );
488+ conn .model (' User' , require (' ../schemas/user' ));
489+
490+ module .exports = conn;
491+ ```
492+
493+ You can create separate files for each connection, like ` connections/web.js ` and ` connections/mobile.js ` if you want to create separate connections for your web API backend and your mobile API backend.
494+ Your business logic can then ` require() ` or ` import ` the connection it needs.
495+
499496<h2 id =" connection_pools " ><a href =" #connection_pools " >Connection Pools</a ></h2 >
500497
501498Each ` connection ` , whether created with ` mongoose.connect ` or
0 commit comments