Node.js


Node.js SDK for SurrealDB
The SurrealDB SDK for Node.js enables simple and advanced querying of a remote database from server-side code. All connections to SurrealDB are made over WebSockets, and automatically reconnect when the connection is terminated.
To contribute to this documentation, edit this file on GitHub.
To contribute to the SDK code, submit an Issue or Pull Request here.
Install the SDK
First, install the SurrealDB SDK using npm:
npm install --save surrealdb.node
Alternatively, you can use install the SurrealDB SDK using yarn, pnpm or similar:
yarn add surrealdb.node
pnpm install surrealdb.node
Connect to SurrealDB
Create a new app.js file and add the following code to try out some basic operations using the SurrealDB SDK.
const { default: Surreal } = require('surrealdb.node');
const db = new Surreal();
async function main() {
try {
// Connect to the database
await db.connect('http://127.0.0.1:8000/rpc');
// Signin as a namespace, database, or root user
await db.signin({
user: 'root',
pass: 'root',
});
// Select a specific namespace / database
await db.use({ ns: 'test', db: 'test' });
// Create a new person with a random id
let created = await db.create("person", {
title: 'Founder & CEO',
name: {
first: 'Tobie',
last: 'Morgan Hitchcock',
},
marketing: true,
identifier: Math.random().toString(36).slice(2, 12),
});
// Update a person record with a specific id
let updated = await db.merge("person:jaime", {
marketing: true,
});
// Select all people records
let people = await db.select("person");
// Perform a custom advanced query
let groups = await db.query('SELECT marketing, count() FROM type::table($tb) GROUP BY marketing', {
tb: 'person',
});
} catch (e) {
console.error('ERROR', e);
}
}
main();
Then run your app from the command line with:
node app.js
SDK methods
The JavaScript SDK comes with a number of built-in functions.
Function | Description |
---|---|
async db.connect(url, options) | Connects to a local or remote database endpoint |
async db.wait() | Waits for the connection to the database to succeed |
async db.close() | Closes the persistent connection to the database |
async db.use({ ns, db }) | Switch to a specific namespace and database |
async db.info() | Returns the record of an authenticated scope user |
async db.signup(vars) | Signs this connection up to a specific authentication scope |
async db.signin(vars) | Signs this connection in to a specific authentication scope |
async db.invalidate() | Invalidates the authentication for the current connection |
async db.authenticate(token) | Assigns a value as a parameter for this connection |
async db.let(key,val) | Runs a set of SurrealQL statements against the database |
async db.unset(key) | Removes a parameter for this connection |
async db.query(sql,vars) | Runs a set of SurrealQL statements against the database |
async db.select(thing) | Selects all records in a table, or a specific record |
async db.create(thing,data) | Creates a record in the database |
async db.insert(thing,data) | Inserts one or multiple records in the database |
async db.update(thing,data) | Updates all records in a table, or a specific record |
async db.merge(thing,data) | Modifies all records in a table, or a specific record |
async db.patch(thing,data) | Applies JSON Patch changes to all records in a table, or a specific record |
async db.delete(thing,data) | Deletes all records, or a specific record |
.connect()
Connects to a local or remote database endpoint.
async db.connect(url, options)
Arguments
Arguments | Description | |
---|---|---|
url | The url of the database endpoint to connect to. | |
options | An object with options to initiate the connection to SurrealDB. |
Example usage
// Connect to a local endpoint
await db.connect('http://127.0.0.1:8000/rpc');
// Connect to a remote endpoint
await db.connect('https://cloud.surrealdb.com/rpc');
.close()
Closes the persistent connection to the database.
async db.close()
Example usage
await db.close();
.use()
Switch to a specific namespace and database. If only the namespace or database property is specified, the current connection details will be used to fill the other property.
db.use({ ns, db })
Arguments
Arguments | Description | |
---|---|---|
ns | Switches to a specific namespace. | |
db | Switches to a specific database. |
Example usage
await db.use({ ns: 'surrealdb', db: 'docs' });
.info()
This method returns the record of an authenticated scope user.
async db.info()
Example usage
const user = await db.info();
.signup()
Signs up to a specific authentication scope.
async db.signup({ ns, db, sc, ... })
Arguments
Properties | Description | |
---|---|---|
ns | The namespace to sign up to | |
db | The database to sign up to | |
sc | The scope to sign up to. Also pass any variables used in the scope |
Example usage
const token = await db.signup({
ns: 'surrealdb',
db: 'docs',
sc: 'user',
// Also pass any properties required by the scope definition
email: 'info@surrealdb.com',
password: '123456',
});
.signin()
Signs in to a root, namespace, database or scope user.
async db.signin({ ... })
Arguments
Properties | Description | |
---|---|---|
user | The username of the database user | |
pass | The password of the database user | |
ns | The namespace to sign in to | |
db | The database to sign in to | |
sc | The scope to sign in to. Also pass any variables used in the scope |
Example usage
// Authenticate with a root user
const token = await db.signin({
user: 'root',
pass: 'surrealdb',
});
// Authenticate with a Namespace user
const token = await db.signin({
ns: 'surrealdb',
user: 'tobie',
pass: 'surrealdb',
});
// Authenticate with a Database user
const token = await db.signin({
ns: 'surrealdb',
db: 'docs',
user: 'tobie',
pass: 'surrealdb',
});
// Authenticate with a Scope user
const token = await db.signin({
ns: 'surrealdb',
db: 'docs',
sc: 'user',
// Also pass any properties required by the scope definition
email: 'info@surrealdb.com',
password: '123456',
});
.invalidate()
Authenticates the current connection with a JWT token.
async db.invalidate()
Example usage
await db.invalidate();
.authenticate()
Authenticates the current connection with a JWT token.
async db.authenticate()
Example usage
await db.authenticate('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA');
.let()
Assigns a value as a parameter for this connection.
async db.let(key, val)
Arguments
Arguments | Description | |
---|---|---|
key | Specifies the name of the variable. | |
val | Assigns the value to the variable name. |
Example usage
// Assign the variable on the connection
await db.let('name', {
first: 'Tobie',
last: 'Morgan Hitchcock',
});
// Use the variable in a subsequent query
await db.query('CREATE person SET name = $name');
// Use the variable in a subsequent query
await db.query('SELECT * FROM person WHERE name.first = $name.first');
.unset()
Removes a parameter for this connection.
async db.unset(key)
Arguments
Arguments | Description | |
---|---|---|
key | Specifies the name of the variable. |
Example usage
// Remove the variable from the connection
await db.unset('name');
.query()
Runs a set of SurrealQL statements against the database.
async db.query(query, vars)
Arguments
Arguments | Description | |
---|---|---|
query | Specifies the name of the variable. | |
vars | Specifies the name of the variable. |
Example usage
// Assign the variable on the connection
const result = await db.query(
'CREATE person SET name = "John"; SELECT * FROM type::table($tb);',
{ tb: 'person' }
);
// Get the first result from the first query
const created = result[0].result[0];
// Get all of the results from the second query
const people = result[1].result;
.select()
Selects all records in a table, or a specific record, from the database.
async db.select(thing)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or a record ID to select. |
Example usage
// Select all records from a table
const people = await db.select('person');
// Select a specific record from a table
const [person] = await db.select('person:h5wxrf2ewk8xjxosxtyc');
Translated query
This function will run the following query in the database:
SELECT * FROM $thing;
.create()
Creates a record in the database.
async db.create(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or the specific record ID to create. | |
data | The document / record data to insert. |
Example usage
// Create a record with a random ID
const [person] = await db.create('person');
// Create a record with a specific ID
const [record] = await db.create('person:tobie', {
name: 'Tobie',
settings: {
active: true,
marketing: true,
},
});
// The content you are creating the record with might differ from the return type
const [record] = await db.create('person:tobie', {
name: 'Tobie',
});
Translated query
This function will run the following query in the database:
CREATE $thing CONTENT $data;
.insert()
Inserts one or multiple records in the database.
async db.insert(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name to insert to. | |
data | Either a single document/record or an array of documents/records to insert |
Example usage
// Insert a single record
const [person] = await db.insert('person', {
name: 'Tobie',
settings: {
active: true,
marketing: true,
},
});
// Insert multiple records
const people = await db.insert('person', [
{
name: 'Tobie',
settings: {
active: true,
marketing: true,
},
},
{
name: 'Jaime',
settings: {
active: true,
marketing: true,
},
},
]);
// The content you are creating the record with might differ from the return type
const people = await db.insert('person', [
{ name: 'Tobie' },
{ name: 'Jaime' },
]);
Translated query
This function will run the following query in the database:
INSERT INTO $thing $data;
.update()
Updates all records in a table, or a specific record, in the database.
async db.update(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or the specific record ID to update. | |
data | The document / record data to insert. |
Example usage
// Update all records in a table
const people = await db.update('person');
// Update a record with a specific ID
const [person] = await db.update('person:tobie', {
name: 'Tobie',
settings: {
active: true,
marketing: true,
},
});
// The content you are updating the record with might differ from the return type
const [record] = await db.update('person:tobie', {
name: 'Tobie',
});
Translated query
This function will run the following query in the database:
UPDATE $thing CONTENT $data;
.merge()
Modifies all records in a table, or a specific record, in the database.
async db.merge(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or the specific record ID to merge. | |
data | The document / record data to insert. |
Example usage
// Update all records in a table
const people = await db.merge('person', {
updated_at: new Date(),
});
// Update a record with a specific ID
const [person] = await db.merge('person:tobie', {
updated_at: new Date(),
settings: {
active: true,
},
});
// The content you are merging the record with might differ from the return type
const [record] = await db.merge('person:tobie', {
name: 'Tobie',
});
Translated query
This function will run the following query in the database:
UPDATE $thing MERGE $data;
.patch()
Applies JSON Patch changes to all records, or a specific record, in the database.
async db.patch(thing, data)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or the specific record ID to patch. | |
data | The JSON Patch data with which to patch the records. |
Example usage
// Update all records in a table
const people = await db.patch('person', [
{ op: 'replace', path: '/created_at', value: new Date() },
]);
// Update a record with a specific ID
const [person] = await db.patch('person:tobie', [
{ op: 'replace', path: '/settings/active', value: false },
{ op: 'add', path: '/tags', value: ['developer', 'engineer'] },
{ op: 'remove', path: '/temp' },
]);
Translated query
This function will run the following query in the database:
UPDATE $thing PATCH $data;
.delete()
Deletes all records in a table, or a specific record, from the database.
async db.delete(thing)
Arguments
Arguments | Description | |
---|---|---|
thing | The table name or a record ID to delete. |
Example usage
// Delete all records from a table
await db.delete('person');
// Delete a specific record from a table
await db.delete('person:h5wxrf2ewk8xjxosxtyc');
Translated query
This function will run the following query in the database:
DELETE * FROM $thing;