When using mongoose.createConnection, how do I access the model from my router? Do I have to mongoose.createConnection every time? Im using this pattern from the docs:
//app.js
const mongoose = require('mongoose');
const conn = mongoose.createConnection(process.env.MONGODB_URI);
conn.model('User', require('../schemas/user'));
conn.model('PageView', require('./schemas/pageView'));
module.exports = conn;
Now, this does not work:
//router.js
const PageView = require('./schemas/pageView');
..I understand that it does not work because I am no longer exporting the model from the schema file, just the schema:
// ./schemas/pageView.js
module.exports = PageViewSchema;
Prior to using createConnection, I've used the default mongoose.connect() in my app.js, so I'd simply export the model, like this:
// ./schemas/pageView.js
const PageView = mongoose.model("PageView", PageViewSchema);
module.exports = PageView;
How can I avoid needing to createConnection in every file I want to use the model?
Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:
const conn = mongoose.createConnection('your connection string'); const MyModel = conn.model('ModelName', schema); const m = new MyModel; m.save(); // works
vs
const conn = mongoose.createConnection('your connection string'); const MyModel = mongoose.model('ModelName', schema); const m = new MyModel; m.save(); // does not work b/c the default connection object was never connected