Any reason you don't post it here so others can chime in as well?
It wasn't just one question, I needed to be able to have a back and forth conversation with someone, and a forum isn't the best platform for that.
However, I'll summarize it in case anyone is interested, or has any other suggestions.
I was trying to make my Node / Express REST API server as modular as possible and follow MVC, so I split it into a bunch of files:
server.js
db.js
routes.js
controllers/controllers.js
models/models.js
I needed to get a reference to the DB connection in models.js in order to query the database. However, since models.js is in a separate folder, using
require('./db')
wouldn't necessarily return the same instance that was originally instantiated.
After some Googling, it looked like there were 2 options:
1. Dependency Injection (DI), which meant passing a reference to either the connection, or something containing it as a parameter to models.js. However, this was a bit clunky, since I had to refactor all the modules into functions, and the connection had to be passed along db.js -> server.js -> routes.js -> controllers.js -> models.js.
2. Global variables or singletons, which are discouraged.
After some back and forth, @BAHayman suggested storing a reference to the connection in app.locals, and then the HTTP method calls in controllers.js have access to that through req.app. Then I just passed it to the individual methods in models.js as a parameter.. Not as clean as I had hoped for, but it seems like the best method given the situation.