Skip to main content

Database Queries

RunJS can connect to any database with a Node.js driver — install the driver from npm and use it as you would in a regular Node script.

Setup

  1. Set the runtime environment to Node.js or Browser & Node.js.
  2. Install the driver for your database.
tip

When working with databases, consider disabling Auto Run — re-running on every change opens a new connection (and runs your queries) each time. Trigger runs explicitly with Cmd/Ctrl+R instead.

SQLite

better-sqlite3 is a synchronous SQLite driver that's well-suited to ad-hoc queries:

import Database from 'better-sqlite3'

const db = new Database('/path/to/data.db')

const rows = db.prepare('SELECT * FROM users WHERE active = ?').all(1)
console.log(rows)

db.close()

Postgres

The pg package is the standard Postgres client. Pull credentials from environment variables so they aren't hard-coded:

import pg from 'pg'

const client = new pg.Client({
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
})

await client.connect()

const { rows } = await client.query('SELECT id, email FROM users LIMIT 10')
console.log(rows)

await client.end()

MongoDB

The official mongodb driver follows the same pattern:

import { MongoClient } from 'mongodb'

const client = new MongoClient(process.env.MONGO_URI)

await client.connect()

const users = client.db('app').collection('users')
const docs = await users.find({ active: true }).limit(10).toArray()
console.log(docs)

await client.close()

Other databases

Any database with a Node driver works the same way — install the package (mysql2, redis, ioredis, etc.) and follow its docs.