Skip to content

Reading data

In this document, you’ll learn how to read data from your database with Typesaurus.

There are several methods that allow reading documents:

  • get - gets a single document by id
  • all - gets all documents in a collection
  • query - queries documents by fields
  • many - gets documents by their ids

get

To get a single document from a collection:

const user = await db.users.get(userId);
// user is null when not found
user?.data.name;
//=> "Sasha"

get is also available on Ref and Doc:

const user = await db.users.get(userId);
// Later:
if (user) {
const freshUser = await user.get();
}

Read more about get

all

To get all documents from a collection:

const users = await db.users.all();
users[0]?.data.name;
//=> "Sasha"

Read more about all

query

To query documents from a collection:

const users = await db.users.query(($) => $.field("name").eq("Alexander"));
users[0]?.data.name;
//=> "Alexander"

Read more about query

many

To get documents by their ids:

const users = await db.users.many([userId1, userId2, userId3]);
users.length;
//=> 3
users[0]?.data.name;
//=> "Tati"

Read more about many

Realtime

You can subscribe to updates by calling .on on any of the reading methods:

db.users
.query(($) => $.field("name").eq("Alexander"))
.on((users) => {
users[0]?.data.name;
//=> "Alexander"
});

The on function returns off, the function that you can call to unsubscribe:

const off = db.users
.query(($) => $.field("name").eq("Alexander"))
.on(processUsers);
// Later:
off();

Read more about realtime