Databases, in general, often hold the most critical data associated with the application–often brokering who can access, update or delete critical compnents which drive other decisions throughout the application. To the greatest extent possible, interactions with this critical application component should be limited to a small subset of co-modules and abstracted away from the main application’s access. _spartan provides these database interaction services.
Database interaction module requires the following dependencies:
require('../security.json')
const mongoose = require('mongoose')
require('./secrets').fetchSecret('DB_CONNECTION')
_spartan assumes database connection information to be SECRET
If you will be using environment variables to manage secrets and wish to include the database connection string, it should be added to your .env
file as ‘DB_CONNECTION’. See secrets.js for more information
Module Instantiation
method name | description | params | returns |
---|---|---|---|
N/A | returns functions to create database connection, models, and new records | todo, String | Error for bad params |
USAGE
const database = require('./security').database
... // the rest of the dependencies & imports
The ‘todo’ parameter toggles 3 options available to the database module: init
, create
, setSchema
Create Connection
method name | description | params | returns |
---|---|---|---|
N/A | establishes the connection to the database at the connection string supplied in .env |
‘init’, String | Success message (String) or Error |
USAGE
...
database('init') // connect to the database
...
Create Model
method name | description | params | returns |
---|---|---|---|
N/A | provides method to create a MongoDB Model | ‘setSchema’, String | Success message (Function) or Error |
N/A | creates a mongoose model | name: name of the db, schema: matching mongoose schema | mongoose model (Model) or Error |
USAGE
...
var newMod = database('setSchema') // returns a function to build a mongoose model
newMod('User', userSchema)
...
Create Record
method name | description | params | returns |
---|---|---|---|
N/A | provides method to create a new record in a specified database | ‘create’, String | Success message (Function) or Error |
N/A | creates a mongoose model | name: name of the db, data: object containing the information to add to the db, callback: handle errors & returned data | newRecord (object) or Error |
USAGE
...
var newRecord = database('create') // returns a function to create a new record
newRecord('User', {fname: 'bob', lname: 'smith', email: 'bob@example.com', uname: 'bobsburgers'}, (err, record) => {
if (err) {
console.log(err.code)
next(err) // assuming you're using Express or similar middleware
} else {
response.redirect('/welcome')
}
})
...
databasePolicy.enabled = true
in security.json.env
file with the DB_CONNECTION variable; and b) that the value of that variable has the format => ‘mongodb://{hostname}:{port}/{dbName}’