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 idall
- gets all documents in a collectionquery
- queries documents by fieldsmany
- 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 founduser?.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();}
all
To get all documents from a collection:
const users = await db.users.all();
users[0]?.data.name;//=> "Sasha"
query
To query documents from a collection:
const users = await db.users.query(($) => $.field("name").eq("Alexander"));
users[0]?.data.name;//=> "Alexander"
many
To get documents by their ids:
const users = await db.users.many([userId1, userId2, userId3]);
users.length;//=> 3users[0]?.data.name;//=> "Tati"
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();