DEV Community

Zach
Zach

Posted on

Mongo Singletons

'Singleton' is a term that I came across a while back when I did some reading, curious about what 'real' programmers know.

It's a design pattern I think.

I ran into singletons in a great Mongo/Mongoose resource I found and then some things I read on Stack Overflow about making Mongoose connections helped to reinforce it.

The Question

How do database connections work?

The question I didn't know I had

How does require work behind the scenes?

The Answer

let mongoose = require('mongoose')
This is the whole enchilada.

On this mongoose instance (I think that's what it is) you:

  • establish the database connection: mongoose.connect(db-server-info-here)
  • write schemas: mongoose.schema(define-your-schema)
  • create models: `mongoose.model(schema-goes-here)
  • execute queries: `mongoose.find(your-search-filter)

Your code doesn't exactly look like that, but that's what's happening.

Usually this all happens across different files. So you'll require Mongoose and then export a connection (or a model, etc).

This is all happening on one instance. One connection: a singleton object.

Here's what one user said on Stack Overflow:

the code in the required module is executed only once. so you can require modules as many times as you want and the connection to mongo db for example will be created only onceMicha Roon Jan 21 '13 at 18:19

And let's round it out with these gems from freecodecamp:

The require(‘mongoose’) call above returns a Singleton object. It means that the first time you call require(‘mongoose’), it is creating an instance of the Mongoose class and returning it. On subsequent calls, it will return the same instance that was created and returned to you the first time because of how module import/export works in ES6.

Similarly, we have turned our Database class into a singleton by returning an instance of the class in the module.exports statement because we only need a single connection to the database.

ES6 makes it very easy for us to create a singleton (single instance) pattern because of how the module loader works by caching the response of a previously imported file.

Top comments (0)