DianaDb ODM for Node.js project
Install DianaDb
(DianaDB Server 4.6.5 works with ODM >= 4.0.0; insertMany and the salted handshake need ODM >= 4.6.5)
npm i -s @diana-db/odm
Upgrading to 4.6.5: server and ODM can be upgraded in any order. ODM 4.6.5 works with a 4.0 server and Server 4.6.5 accepts ODM 4.0 while
legacy_auth is on. Once both are on 4.6.5, see Security for switching the earlier handshake off. 4.6.6 – 4.6.13 (ODM 4.6.9) are fixes on top of 4.6.5; see the changelog for the behavior that changed with them.
Upgrading to 4.0.0: upgrade the ODM first. ODM versions before 4.0.0 reject VECTOR fields, and reject
_ids in queries when the server sets server_id. See the changelog for other behavior changes. Upgrading to 3.0.0: Server 3.0.0 closes subscriber connections that don't send a token, which ODM versions before 3.0.0 don't do. Upgrade the ODM first (it works with the older server too), then the server. See the changelog for the other breaking changes.
Create DianaDb instance
import { readFileSync } from 'node:fs';
import { DianaDb } from '@diana-db/odm';
export const dianaDb = new DianaDb({
host: 'db.example.com',
port: 34567, // 1025–65535
user: 'db_user',
password: 'some-password',
connectionPoolSize: 5,
connectTimeoutValue: 5000,
reconnectTimeoutValue: 1000,
requestTimeoutValue: 30000,
database: 'test', // default database for migrations (optional)
secureServer: true, // if your server uses TLS
tls: {
ca: readFileSync('/path/to/ca'), // CA that signed the server certificate
cert: readFileSync('/path/to/cert'), // only for mTLS
key: readFileSync('/path/to/key'), // only for mTLS
},
});
await dianaDb.connect(5000);
A connection string may be used instead:
import { DianaDb } from '@diana-db/odm';
export const dianaDb = new DianaDb('diana-db://user:pass@localhost:34567?connectionPoolSize=5');
// TLS, with "test" as the default database for migrations
export const dianaDbS = new DianaDb('diana-dbs://user:pass@db.example.com:34567/test');
The connection string accepts connectionPoolSize, connectTimeoutValue, reconnectTimeoutValue, requestTimeoutValue and legacyAuth as query parameters, and rejectUnauthorized=false with diana-dbs://. The optional path sets the database option. User name and password are URL-decoded, so encode special characters (p%40ss for p@ss). diana-dbs:// sets secureServer: true; any other protocol throws a configuration error.
You can create as many instances as you like. Each has its own migrations and subscribers and connects independently. A model sends its requests through the instance passed as
dianaDb in its options, or else through the instance most recently constructed before the model. Connection behaviour
connect()resolves as soon as one pooled connection is up; the others connect in the background.- If every connection is down (server restart, network blip), new requests are queued and sent when a connection is back, or fail with a
TIMEOUTerror afterrequestTimeoutValue. - Requests already sent on a connection that drops fail immediately with a
CONNECTIONerror instead of waiting for their timeout. - A wrong password fails the request at once with a message naming the likely cause: the server closes connections whose requests it cannot decrypt.
- After
disconnect()requests fail immediately untilconnect()is called again.disconnect()also closes the subscriber connection, so the Node.js process can exit.
Every failed request rejects with an error carrying a code, see Errors.
DianaDb Constructor Options
| Property | Description | Format | Default Value |
|---|---|---|---|
host | Server host. Required | String | – |
port | Server port | Integer, 1025–65535 | 34567 |
user | Username. Required | String | – |
password | Password. Required | String | – |
connectionPoolSize | Number of pooled connections | Positive integer | 5 |
connectTimeoutValue | Connection timeout in milliseconds | Positive integer | 30000 |
reconnectTimeoutValue | Delay between reconnection attempts in milliseconds | Positive integer | 1000 |
requestTimeoutValue | Default timeout of every request in milliseconds | Positive integer | 30000 |
database | Database used by migrateUp, migrateDown and getMigrations when called without one | String | – |
secureServer | Whether the server uses TLS | Boolean | false |
tls | { ca?, rejectUnauthorized?, servername?, cert?, key? }. Values are Buffers (readFileSync) or PEM strings; ca may be an array; other Node.js tls.connect options pass through. cert/key are only needed when the server verifies clients (mTLS) | Object | – |
legacyAuth | Fall back to the earlier handshake when the server is older than 4.6.5. false refuses such servers. Also accepted as ?legacyAuth=false in a connection string. See Security | Boolean | true |
logger | Logger with log and error | Object | console |
Since 4.6.10 the server's certificate is checked unless you turn that off: against the system's certificate authorities, or against
ca when you pass one, and against host (or servername), so connect by the name in the certificate, not by IP. For a certificate signed by your own CA pass ca; a connection string can't carry one, so use the options object, or Node's NODE_EXTRA_CA_CERTS. tls.rejectUnauthorized: false (or ?rejectUnauthorized=false) connects without checking: the traffic is encrypted, but anyone between client and server can read and change it, so keep it to development. Before 4.6.10 the default was not to check. Client Methods
| Method | Arguments | Description | Return Type |
|---|---|---|---|
connect | connectTimeoutValue?: positive integer | Connects to the server. Rejects with a CONNECTION error after the timeout | Promise<boolean> |
disconnect | – | Closes every connection, the subscriber connection included. Pending requests fail at once | Promise<void> |
subscribe | key: string, subscriber: (update: DatabaseUpdate) => void — Subscribers | Adds a subscriber for database or collection changes. Several per key are allowed | Promise<void> |
unsubscribe | key: string, subscriber? | Removes one subscriber, or every subscriber of the key. Closes the subscriber connection when none are left | Promise<void> |
addMigration | migration: Migration | Registers a migration script. Throws if its index or name is already used | void |
migrateUp | database?: string | Applies pending migrations in ascending index order | Promise<MigrationInfo[]> |
migrateDown | database?: string, steps?: number | Reverts applied migrations in descending index order — all, or the last steps | Promise<MigrationInfo[]> |
getMigrations | database?: string | Names of the migrations recorded as applied on the server | Promise<string[]> |
startTransaction | StartTransactionParameters: object | Starts a transaction with an optional auto-rollback | Promise<string> (transactionId) |
commitTransaction | ManageTransactionParameters: object | Commits an open transaction | Promise<TransactionInfo> |
rollbackTransaction | ManageTransactionParameters: object | Rolls back an open transaction | Promise<TransactionInfo> |
getDatabases | – | Names of the databases the current user can read | Promise<string[]> |
createDatabase | database: string | Creates an empty database. Requires manage access to it | Promise<{ database: string; action: 'created' }> |
removeDatabase | database: string | Removes a database | Promise<{ database: string; action: 'removed' }> |
getCollections | database: string | Collection names in a database | Promise<string[]> |
createCollection | database: string, collection: string, schema: Schema | Creates a collection | Promise<{ collection: string; action: 'created' }> |
removeCollection | database: string, collection: string | Removes a collection | Promise<{ collection: string; action: 'removed' }> |
getCollectionSchema | database: string, collection: string | Stored schema and its lock state | Promise<{ schema: Schema; locked: boolean }> |
getCollectionSchemaLock | database: string, collection: string | Lock state of the schema | Promise<{ collection: string; locked: boolean }> |
lockCollectionSchema | database: string, collection: string | Locks the schema | Promise<{ collection: string; locked: boolean }> |
unlockCollectionSchema | database: string, collection: string | Unlocks the schema | Promise<{ collection: string; locked: boolean }> |
getCollectionViews | database: string, collection: string | Materialized views defined on a collection | Promise<Record<string, { transformQueries }>> |
getHealth | – | Current server health | Promise<HealthInfo> |
getVersion | – | Server version | Promise<{ version: string }> |
type HealthInfo = {
memory: number; // memory usage (MB)
cpu: number; // CPU usage (%)
gcp: number; // garbage collector pressure (%)
elu: number; // event loop utilization (%)
eld: number; // event loop delay (ms)
};