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 parameter being the document to insert.
const docId = (await zkdb.db(databaseName)
.collection<SchemaType>(collectionName)
.insert(document)).unwrap();
Parameters
document: The object containing the data to be inserted into the collection. It should match the schema of the collection.
Returns
The function returns a Result that contains the document ID upon successful insertion. Use .unwrap() to get the value or check with .isOk() / .isErr().
Example
The example shows how to insert documents into the collection.
import { ZkDatabase } from 'zkdb';
const zkdb = new ZkDatabase({
apiKey: 'zkdb_536aac02a1b7.c001b6b8f...da3aa4185d8d2ad07f0ae94aT',
// This URL is for test environment
url: "https://serverless.zkdatabase.org/graphql",
});
// Define the schema
const ShirtSchema = new Schema([
{ name: 'name', kind: 'String' },
{ name: 'price', kind: 'UInt64' },
]);
type TShirt = SchemaToObject<
ReturnType<typeof ShirtSchema.schemaDefinition>
>;
const collection = zkdb.db('zkdb_test').collection<TShirt>('shirt');
// Insert a document
const result = (
await collection.insert({
name: 'Test Shirt',
price: 10n,
})
).unwrap();
console.log('Inserted document with ID:', result);
// Insert with permission
const resultSecure = (
await collection.insert(
{
name: 'Orochi',
price: 10n ** 9n,
},
Permission.policyStrict()
)
).unwrap();
console.log('Inserted secure document:', resultSecure);