Insert Document
The zkDatabase library provides the insert
method to add new documents to a specified collection within a database. This method supports both basic and advanced usage, allowing you to specify detailed permissions for different users or groups.
Definition
The insert
function is called on a collection object, with the first parameter being the document to insert and an optional second parameter for permissions.
await zkdb.db(databaseName: string)
.collection(collectionName: string)
.insert(
document: Record<string, TSerializedValue>,
permission?: number
): Promise<TDocumentCreateResponse>;
Parameters
document
(Record<string, TSerializedValue>): The object containing the data to be inserted into the collection. It should match the schema of the collection, e.g.{ name: 'Shirt 1', price: 15 }
.permission
(number, optional): A permission policy object that defines how the document insertion is exposed in terms of security or access control.
Returns
Promise<TDocumentCreateResponse>
: Returns the created document with its unique ID and metadata. The document is immediately available for queries and will be included in the next zero-knowledge proof generation cycle. The response includes the document's sequence number for tracking in rollup operations.
type TDocumentCreateResponse = {
docId: string;
acknowledged: boolean;
document: Record<string, TSchemaSerializedField>;
};
Example
import { CircuitString, UInt64 } from 'o1js';
import { Schema, ZkDatabase, Permission } from 'zkdb';
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');
await collection.insert({
name: 'Test Shirt',
price: 10n,
});
await collection.insert(
{
name: 'Orochi',
price: 10n ** 9n,
},
Permission.policyStrict()
);
await zkdb.auth.signOut();