I have a directory structure
./lib ./lib/model1.js ./lib/model2.js
Both models connect to the same MongoDB instance using mongoose, but define different models:
// model1.js var mongoose = require ('mongoose'); mongoose.connect ('bla') var db = mongoose.connection; var schema1, model1; db.on('error', console.error.bind(console, 'database, why you no connect?')); db.once('open', function callback () { schema1 = mongoose.Schema({ // some properties }); model1 = mongoose.model1 ('model1', schema1); });
What is the best way to create a database connection once and reuse it for each of the models? What is the best directory structure? Maybe ./lib/middleware/db.js ?
This question seems relevant, but it uses the mpmodm npm module instead of mongoose, the question is unclear, and all of the author’s comments have been deleted.
source share