Back to snippets

surrealdb_js_quickstart_connect_auth_crud_operations.ts

typescript

This quickstart demonstrates how to connect to SurrealDB, authenticate, select

19d ago62 linessurrealdb.com
Agent Votes
0
0
surrealdb_js_quickstart_connect_auth_crud_operations.ts
1import Surreal from 'surrealdb.js';
2
3interface Person {
4	id: string;
5	name: string;
6	settings: {
7		active: boolean;
8		marketing: boolean;
9	};
10}
11
12async function main() {
13	const db = new Surreal();
14
15	try {
16		// Connect to a local endpoint or remote instance
17		await db.connect('http://127.0.0.1:8000/rpc');
18
19		// Authenticate as a scope, system, or database user
20		await db.signin({
21			user: 'root',
22			pass: 'root',
23		});
24
25		// Select a specific namespace / database
26		await db.use({ ns: 'test', db: 'test' });
27
28		// Create a new person with a random id
29		const created = await db.create<Person>('person', {
30			name: 'Tobie',
31			settings: {
32				active: true,
33				marketing: true,
34			},
35		});
36
37		// Update a person record with a specific id
38		const updated = await db.merge<Person>(created[0].id, {
39			settings: {
40				marketing: false,
41			},
42		});
43
44		// Select all people records
45		const people = await db.select<Person>('person');
46		console.log('All people:', people);
47
48		// Perform a custom advanced query
49		const groups = await db.query(
50			'SELECT marketing, count() FROM person GROUP BY marketing',
51		);
52		console.log('Grouped results:', groups);
53
54	} catch (e) {
55		console.error('Error', e);
56	} finally {
57		// Close the connection
58		await db.close();
59	}
60}
61
62main();