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.
Alternatively, you can use install the SurrealDB SDK using yarn, pnpm or similar:
yarnadd surrealdb.node
pnpminstall 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 =newSurreal();asyncfunctionmain(){try{// Use any of these 3 connect methods to connect to the database// 1.Connect to the databaseawait db.connect('http://127.0.0.1:8000/rpc');// 2. Connect to database serverawait db.connect('ws://127.0.0.1:8000');// 3. Connect via rocksdb fileawait db.connect(`rocksdb://${process.cwd()}/test.db`);// Signin as a namespace, database, or root userawait db.signin({username:'root',password:'root',});// Select a specific namespace / databaseawait db.use({namespace:'test',database:'test'});// Create a new person with a random idlet 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 idlet updated =await db.merge('person:jaime',{marketing:true,});// Select all people recordslet people =await db.select('person');// Perform a custom advanced querylet 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.
An object with options to initiate the connection to SurrealDB.
// Connect to a local endpointawait db.connect('http://127.0.0.1:8000/rpc');// Connect to a remote endpointawait db.connect('https://cloud.surrealdb.com/rpc');// Specify a namespace and database pair to useawait db.connect('https://cloud.surrealdb.com/rpc',{namespace:'surrealdb',database:'docs',});// Authenticate with an existing token// The .authenticate() function is used under the hood.await db.connect('https://cloud.surrealdb.com/rpc',{auth:'.....',});// Authenticate using a pair of credentialsawait db.connect('https://cloud.surrealdb.com/rpc',{auth:{username:'root',password:'surrealdb',},});
async db.close()
Closes the persistent connection to the database.
await db.close();
db.use({ namespace, database })
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.
The scope to sign up to. Also pass any variables used in the scope
const token =await db.signup({namespace:'surrealdb',database:'docs',scope:'user',// Also pass any properties required by the scope definitionemail:'info@surrealdb.com',password:'123456',});
async db.signin({...})
Signs in to a root, namespace, database or scope user.
Properties
Description
usernameRequired for root, NS & DB
The username of the database user
passwordRequired for root, NS & DB
The password of the database user
namespaceRequired for DB & SC
The namespace to sign in to
databaseRequired for SC
The database to sign in to
scope
The scope to sign in to. Also pass any variables used in the scope
// Authenticate with a root userconst token =await db.signin({username:'root',password:'surrealdb',});// Authenticate with a Namespace userconst token =await db.signin({namespace:'surrealdb',username:'tobie',password:'surrealdb',});// Authenticate with a Database userconst token =await db.signin({namespace:'surrealdb',database:'docs',username:'tobie',password:'surrealdb',});// Authenticate with a Scope userconst token =await db.signin({namespace:'surrealdb',database:'docs',scope:'user',// Also pass any properties required by the scope definitionemail:'info@surrealdb.com',password:'123456',});
async db.invalidate()
Invalidates the authentication for the current connection.
await db.invalidate();
async db.authenticate(token)
Authenticates the current connection with a JWT token.
Assigns a value as a parameter for this connection.
Arguments
Description
keyRequired
Specifies the name of the variable.
valRequired
Assigns the value to the variable name.
// Assign the variable on the connectionawait db.let('name',{first:'Tobie',last:'Morgan Hitchcock',});// Use the variable in a subsequent queryawait db.query('CREATE person SET name = $name');// Use the variable in a subsequent queryawait db.query('SELECT * FROM person WHERE name.first = $name.first');
async db.unset(key)
Removes a parameter for this connection.
Arguments
Description
keyRequired
Specifies the name of the variable.
// Remove the variable from the connectionawait db.unset('name');
async db.query(query, vars)
Runs a set of SurrealQL statements against the database.
Arguments
Description
queryRequired
Specifies the SurrealQL statements.
varsOptional
Assigns variables which can be used in the query.
// Assign the variable on the connectionconst result =await db.query('CREATE person SET name = "John"; SELECT * FROM type::table($tb);',{tb:'person'});// Get the first result from the first queryconst created = result[0].result[0];// Get all of the results from the second queryconst people = result[1].result;
async db.select(thing)
Selects all records in a table, or a specific record, from the database.
Arguments
Description
thingRequired
The table name or a record ID to select.
// Select all records from a tableconst people =await db.select('person');// Select a specific record from a tableconst[person]=await db.select('person:h5wxrf2ewk8xjxosxtyc');
This function will run the following query in the database:
SELECT*FROM$thing;
async db.create(thing, data)
Creates a record in the database.
Arguments
Description
thingRequired
The table name or the specific record ID to create.
dataOptional
The document / record data to insert.
// Create a record with a random IDconst[person]=await db.create('person');// Create a record with a specific IDconst[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 typeconst[record]=await db.create('person:tobie',{name:'Tobie',});
This function will run the following query in the database:
CREATE$thingCONTENT$data;
async db.insert(thing, data)
Insers one or multiple records in the database.
Arguments
Description
thingRequired
The table name to insert to.
dataOptional
Either a single document/record or an array of documents/records to insert
// Insert a single recordconst[person]=await db.insert('person',{name:'Tobie',settings:{active:true,marketing:true,},});// Insert multiple recordsconst 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 typeconst people =await db.insert('person',[{name:'Tobie'},{name:'Jaime'},]);
This function will run the following query in the database:
INSERT INTO$thing$data;
async db.update(thing, data)
Updates all records in a table, or a specific record, in the database.
This function replaces the current document / record data with the specified data.
Arguments
Description
thingRequired
The table name or the specific record ID to update.
dataOptional
The document / record data to insert.
// Update all records in a tableconst people =await db.update('person');// Update a record with a specific IDconst[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 typeconst[record]=await db.update('person:tobie',{name:'Tobie',});
This function will run the following query in the database:
UPDATE$thingCONTENT$data;
async db.merge(thing, data)
Modifies all records in a table, or a specific record, in the database.
This function merges the current document / record data with the specified data.
Arguments
Description
thingRequired
The table name or the specific record ID to merge
dataOptional
The document / record data to insert.
// Update all records in a tableconst people =await db.merge('person',{updated_at:newDate(),});// Update a record with a specific IDconst[person]=await db.merge('person:tobie',{updated_at:newDate(),settings:{active:true,},});// The content you are merging the record with might differ from the return typeconst[record]=await db.merge('person:tobie',{name:'Tobie',});
This function will run the following query in the database:
UPDATE$thingMERGE$data;
async db.patch(thing, data)
Applies JSON Patch changes to all records, or a specific record, in the database.
This function patches the current document / record data with the specified JSON Patch data.
Arguments
Description
thingRequired
The table name or the specific record ID to patch.
dataOptional
The JSON Patch data with which to patch the records.
// Update all records in a tableconst people =await db.patch('person',[{ op:'replace', path:'/created_at', value:newDate()},]);// Update a record with a specific IDconst[person]=await db.patch('person:tobie',[{ op:'replace', path:'/settings/active', value:false},{ op:'add', path:'/tags', value:['developer','engineer']},{ op:'remove', path:'/temp'},]);
This function will run the following query in the database:
UPDATE$thing PATCH $data;
async db.delete(thing)
Deletes all records in a table, or a specific record, from the database.
Arguments
Description
thingRequired
The table name or a record ID to delete.
// Delete all records from a tableawait db.delete('person');// Delete a specific record from a tableawait db.delete('person:h5wxrf2ewk8xjxosxtyc');
This function will run the following query in the database: