Skip to content

Instantly share code, notes, and snippets.

@tjkhara
Last active November 11, 2020 17:50
Show Gist options
  • Select an option

  • Save tjkhara/dea40be7586f36e93e2f3ee15fcb2c3f to your computer and use it in GitHub Desktop.

Select an option

Save tjkhara/dea40be7586f36e93e2f3ee15fcb2c3f to your computer and use it in GitHub Desktop.
Connecting to db in a reusable fashion

Connecting to db

Part 1

Save registered user into the db

model -> register function

validation is done now

Create new db in atlas

db name - ComplexApp collection name - users

In the root create new file - db.js

npm install mongodb

Require the file

const mongodb = require('mongodb')

const connectionString = 'conn string'

mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
	module.exports = client.db()
})

Make db startup file

Open app.js

Go to end

delete app.listen line

module.exports = app

Go to db

const app = require('./app')
app.listen(3000)

Part 2

package.json

change in watch app to db

test

Correct this function

mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: false}, function(err, client){
  module.exports = client.db()
  const app = require('./app')
  app.listen(3000)
})

The app in this structure will not begin till we've had a chance to export the mongodb database.

Now we can work with the database in any file where we just require the db.js file.

Now we will use db in model file

in model const usersCollection = require('../db').collection("users")

Now we can perform crud on this usersCollection variable.

in register

check for validation errors

if(!this.errors.length){
	usersCollection.insertOne(this.data)
}

test this out

fill in the form - value should be in db

Part 3 - setting up environment variables

db.js

new file - .env

setup connectionstring and port

in db.js

npm install dotenv

Top line

const dotenv = require('dotenv')

dotenv.config()

in the mongodb.connect() function

replace first argument with

process.env.CONNECTIONSTRING

test app

Do same thing for port

go to .env

PORT=3000

in db.js

app.listen(process.env.port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment