I have a NodeJS app that currently utilizes a single mongo database, but I find myself in need of grabbing the data that is on a secondary database. Both databases are on the same cluster. The project structure is as follow:
app.js
models
--Book.js
--School.js
--Class.js
--User.js
routes
--adoptions.js
views
--handlebars files
In the app.js I've always used mongoose.connect() but I understood that this basically "maps" that mongoose connection with the global connection, so what I'm trying to use is mongoose.createConnection().
All the questions and answers I've found have the models and the connection objects in the same file, but in my project they are in different files.
An other problem is that the models are not the same on the different databases: Database1 has only one collection of users, Database2 has Book, School and Class.
I'm struggling to retrieve data from the second database, even if I define a connection object in the routes file. I've tried to put:
var conn = mongoose.createConnection('connectionStringToDatabase2', {useNewUrlParser: true});
const Class = conn.model('class');
const Book = conn.model('book');
const School = conn.model('school');
inside my adoptions.js file but when I execute a find() query on any of them I get an empty array even though I know they contain data.
My model files look like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Create Schema
const BookSchema = new Schema({
//Various schema stuff
}, { _id: false });
mongoose.model('book', BookSchema, 'book');
and the rest of the schemas follow the same structure.
How can I use the secondary connection, while still retaining my project structure? I don't really want to have one huge file with everything in it, and I know I'm missing something here
const mongoose1 = require('mongoose');andconst mongoose2 = require('mongoose');and see if you could have multiple modules loaded at the same time