Back

[CLOSED] How to update an array attribute?

  • 0
  • Web
ViharGandhi
21 May, 2023, 13:53

I have defined an attribute that is an array of strings. Now, I would like to know how to add a new string element to the array. What would be the appropriate query or method to accomplish this?

TL;DR
OP is asking for guidance on how to update an array attribute in their code. They provided their current code but are unsure about how to get a unique document ID. Another user provided an example code snippet on how to update an array attribute. To update an array attribute, the user can use the `updateDocument` method with the appropriate parameters. They can pass in the document ID, the name of the array attribute, and a new array that includes the existing elements along with the new element they want to add.
Drake
21 May, 2023, 15:33

How to update an array attribute?

Binyamin
21 May, 2023, 18:57

The example for that it would be something like this, will assume the field phones is an array and you'll like to add one phone.

TypeScript
const newPhone = '131331';

try {
  // Get the current document
  const doc = await database.getDocument('[DATABASE_ID]', '[COLLECTION_ID]', '[DOCUMENT_ID]');

  // Updating the document. adding the phone at the end of the array attribute 
  await const promise = databases.updateDocument('[DATABASE_ID]', '[COLLECTION_ID]', '[DOCUMENT_ID]',{
    phones: [...doc.phones, newPhone]
  });

} catch (e) {
  // handle error.
}
ViharGandhi
22 May, 2023, 04:30

but everytime a unique documentid goes in the DB so how do we get that ??

ViharGandhi
22 May, 2023, 05:04

i approached it something like this const promise0 = await databases.listDocuments('DATABASEID', 'COLLECTIONID', [ Query.equal('Email', Email) ]);

if (promise0.total === 1) { let arr = promise0.documents[0].writtenthings; arr.push(content); const promise = databases.updateDocument( 'DATABASEID', 'COLLECTIONID', promise0.documents[0].$id, { writtenthings: arr } ); }

if (promise0.total === 0) { const arr = [content]; const promise = databases.createDocument( 'DATABASEID', 'COLLECTIONID', 'unique()', { Email: Email, writtenthings: arr } ); }

joeyouss
25 May, 2023, 18:53

[CLOSED] How to update an array attribute?

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