createDocument / store
Creates a new document with automatic ID and timestamp generation.
const user = await client.createDocument(
'users',
{ email: 'alice@example.com', name: 'Alice', active: true },
{
payment_tx_hash: 'tx_hash',
user_address: 'celestia1...',
broker_address: 'celestia1broker...',
amount_utia: 100000
},
{
idGenerator: () => 'custom_id_123' // Optional: custom ID generator
}
);
// Auto-adds: id, createdAt, updatedAt
console.log(user.id); // 'custom_id_123'
console.log(user.createdAt); // '2024-01-01T00:00:00.000Z'
Parameters
| Parameter | Type | Description |
|---|
collection | string | Collection name |
data | object or array | Document data (single or array) |
paymentProof | PaymentProof | Payment information |
options | CreateOptions | Optional configuration |
Auto-Generated Fields
When you create a document, the SDK automatically adds:
| Field | Type | Description |
|---|
id | string | Unique document ID (UUID v4 by default) |
createdAt | string | ISO 8601 timestamp |
updatedAt | string | ISO 8601 timestamp (same as createdAt on create) |
TypeScript SDK auto-generates these fields. In Go, PHP, and Python, you should add them manually or use helper functions.
Bulk Creation
For creating multiple documents at once:
const result = await client.store(
{
collection: 'users',
data: [
{ email: 'alice@example.com', name: 'Alice' },
{ email: 'bob@example.com', name: 'Bob' },
{ email: 'charlie@example.com', name: 'Charlie' }
]
},
async (quote) => {
const txHash = await wallet.pay(quote.brokerAddress, quote.totalCostTia);
return { txHash, network: 'mocha-4' };
},
true
);
console.log('Stored at block:', result.block_height);
Error Handling
import { ValidationError, OnchainDBError } from '@onchaindb/sdk';
try {
const user = await client.createDocument('users', { email: 'alice@example.com' }, paymentProof);
} catch (error) {
if (error instanceof ValidationError) {
console.log('Validation failed:', error.message);
} else if (error instanceof OnchainDBError) {
console.log('OnchainDB error:', error.code);
}
}
Next Steps