Mongoose saving
So, the output of mongoose.model()
is a model, and a given model is always tied to one connection.
By default, most folks just use the connection and connection pooling available from mongoose.connect()
. Once you call that, the cached mongoose module is using a singleton connection object under the hood. So for example, if I'm calling your model, I'd do this:
const mongoose = require('mongoose');const User = require('./models/user');mongoose.connect(); // or pass in a custom URL// from here, User will default to the mongoose-internal connection created in the previous line
If I want to use multiple connections, I cannot use the mongoose internal singleton, so I would have to do the operations with the created connection. For example:
// ./schemas/user.js// You now export the Schema rather than the module in your file//module.exports = mongoose.model('User', User);module.exports = User;
Then in the calling code:
const config = require('./config'); // presumably this has a couple mongo URLsconst mongoose = require('mongoose');const UserSchema = require('./schemas/user');const conn1 = mongoose.createConnection(config.url1);const conn2 = mongoose.createConnection(config.url2);const User1 = conn1.model('User', UserSchema);const User2 = conn2.model('User', UserSchema);// now any users created with User1 will save to the first db, users created with User2 will save to the second.