Back

Cannot create documents using custom id in web (works if in console)

  • 0
  • Databases
  • Web
  • Cloud
Kushl121
21 Feb, 2024, 20:05
TypeScript
import { Client, Databases, ID } from "appwrite";

const client = new Client()
    .setEndpoint('https://cloud.appwrite.io/v1')
    .setProject('<PROJECT_ID>');
const databases = new Databases(client);
const id = Date.now(); //this does not work, error recieved is shown after code ends
const promise = databases.createDocument(
    '[DATABASE_ID]',
    '[COLLECTION_ID]',
    id,
    data
);

promise.then(function (response) {
    console.log(response);
}, function (error) {
    console.log(error);
});

error: AppwriteException: Invalid documentId param: Parameter must contain at most 36 chars. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char

But the same method works in upload file:

TypeScript
import { Client, Storage } from "appwrite";

const client = new Client();

const storage = new Storage(client);

client
    .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
;
const id = Date.now() //this works and file is created
const promise = storage.createFile('[BUCKET_ID]', id, document.getElementById('uploader').files[0]);

promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});
TL;DR
When creating documents with a custom ID in a web app, make sure to convert Date.now() to a string. The document ID should contain at most 36 characters and valid characters are a-z, A-Z, 0-9, period, hyphen, and underscore. It cannot start with a special character. The error occurs because the ID generated by Date.now() exceeds the character limit. To fix this, convert the ID to a string using Date.now().toString() before passing it to the createDocument function.
Kushl121
21 Feb, 2024, 20:12

Cannot create documents using custom id in web (works if in console)

Evdog
21 Feb, 2024, 20:52

Date.now() returns an int, and the document ID needs to be a string. so you can do something like const id = Date.now().toString()

You can review the docs here to see the properties and their type expectancies here: https://appwrite.io/docs/references/cloud/models/document

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more