MasterRecord

Connecting a Database

Two ways to configure your connection — inline, or per-environment files.

A context connects your models to a database. Configure it in its constructor with this.env(...), passing either an inline config object or a folder of environment files.

Inline configuration#

The quickest way to get going — pass a config object directly:

AppContext.js
import context from 'masterrecord/context';
import User from './User.js';

class AppContext extends context {
  constructor() {
    super();
    this.env({ type: 'better-sqlite3', connection: 'db/' });
    this.dbset(User);
  }
}

export default AppContext;
Note
Inline-object support was fixed in MasterRecord 1.3.0. On earlier versions, use the environment-file form below.

Point this.env() at a folder and MasterRecord loads env.<NODE_ENV>.json. The file is keyed by the context class name, so one file can hold many contexts.

AppContext.js
class AppContext extends context {
  constructor() {
    super();
    this.env('config/environments'); // loads env.<NODE_ENV>.json
    this.dbset(User);
  }
}
config/environments/env.development.json
{
  "AppContext": {
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "database": "myapp_dev",
    "user": "postgres",
    "password": "dev_password"
  }
}

Per-engine configuration#

SQLite#

Zero setup. connection is a file path, or a directory ending in / to auto-create <contextname>.sqlite. Use a relative path (db/, not /db/).

sqlite
{ "AppContext": { "type": "better-sqlite3", "connection": "db/" } }

MySQL#

mysql
{
  "AppContext": {
    "type": "mysql",
    "host": "127.0.0.1", "port": 3306,
    "database": "myapp", "user": "root", "password": "",
    "connectionLimit": 10
  }
}

PostgreSQL#

postgres
{
  "AppContext": {
    "type": "postgres",
    "host": "localhost", "port": 5432,
    "database": "myapp", "user": "postgres", "password": "password",
    "max": 20, "idleTimeoutMillis": 30000
  }
}
Async engines
MySQL and PostgreSQL connect asynchronously — await your queries and saveChanges(). SQLite is synchronous but the same await-friendly API works across all three, so your code stays portable.

Selecting the environment#

terminal
NODE_ENV=production node server.js
# or with MasterRecord's own env var:
master=production node server.js