Find Document
The findOne
and findMany
methods are used to retrieve documents from a collection in a Zero-Knowledge Database (zkDatabase). These methods allow querying the database based on specified criteria, supporting both single document fetches and bulk retrievals.
Definition
The findOne
function retrieves a single document that matches the given filter criteria, while the findMany
function fetches all documents that match the filter.
await collection.findOne(filter: Record<string, any> | undefined): Promise<Document>;
await collection.findMany(filter: Record<string, any> | undefined, pagination?: TPagination): Promise<TPaginationReturn<Document[]>>;
Parameters
filter
:Record<string, any>
- An object representing the criteria to be used for filtering documents within the collection. Each key-value pair corresponds to a document field and the desired value for that field (e.g.,{ name: 'Test Shirt' }
).pagination
:TPagination
- An optional object that specifies pagination parameters for the query. This can be used to retrieve a subset of documents based on their position in the collection (e.g:{ limit: 5, offset: 0 }
).
Returns
findOne
: Returns aPromise
that resolves to a singleDocument
object if a matching document is found. If no document matches the criteria, it may resolve tonull
orundefined
.findMany
: Returns aPromise
that resolves to an array ofTPaginationReturn<Document[]>
objects, representing all documents that match the given filter. The array will be empty if no documents match the criteria.
type TPaginationReturn<T> = {
data: T;
total: number;
offset: number;
};
Example
Here is an example demonstrating how to use findOne
and findMany
to retrieve documents from a collection:
import { CircuitString, UInt64 } from 'o1js';
import { Schema, ZkDatabase, Permission } from './index';
const zkdb = await ZkDatabase.connect({
userName: "chiro-user",
privateKey: "EKFTciRxyxshZjimay9sktsn7v5PvmC5zPq7q4JnitHUytxUVnFP",
environment: "node",
// This URL is for test environment
url: "https://api.zkdatabase.org/graphql",
});
await zkdb.auth.signIn();
class Shirt extends Schema.create({
name: CircuitString,
price: UInt64,
}) {}
type TShirt = typeof Shirt;
const collection = await zkdb
.db('zkdb_test')
.collection<TShirt>('test_collection');
const doc = await collection.findOne({ name: 'Test Shirt' });
if (doc) {
console.log(doc.document);
}
const listDoc = await collection.findMany(undefined, { limit: 10, offset: 0 });
listDoc.data.forEach((item) => {
console.log(item.document);
});
await zkdb.auth.signOut();