How do I delete all rows from a table?
# 🤝help
d
I have been struggling trying to get the syntax right. I want to clear out a table called ListOfItems If I do
Copy code
// Delete all rows from the ListOfItems
await ListOfItems.deleteRecords([])
It says I must set deleteAllRows to true.... How do I do this? If I try something like this it also complains....
Copy code
await ListOfItems.deleteRecords({
  ids: [],
  deleteAllRows: true
})
Silly issue but hope some one can give me a clue... Thanks
w
Hi ! here is an example of code that works 🙂
Copy code
async function deleteAllRecords() {
  try {
    const data = await messagesTable.findRecords({ filter: AI`Everything` })

    if (!Array.isArray(data)) {
      console.log('No records found.')
      return
    }

    const recordIDs = data.map((record) => record.id)

    if (recordIDs.length > 0) {
      await messagesTable.deleteRecords(recordIDs)
      console.log('Old records deleted.')
    } else {
      console.log('No records to delete.')
    }
  } catch (error) {
    console.log(error)
  }
}

await deleteAllRecords()
d
Thanks OOOBo, quite a script just to drop all rows when the documentation https://botpress.com/docs/cloud/studio/tables/#delete-records-from-a-table I get the idea it should just be a one or two line command?
w
in fact, if you look closely, there are only 3 lines 😉
`const data = await messagesTable.findRecords({ filter: AI`Everything` })`
const recordIDs = data.map((record) => record.id)
await messagesTable.deleteRecords(recordIDs)
3 lines that can be condensed in 2😅
even in 1 lol
actually i giveb you something that works, but to be honest i had never tested the one from the doc
d
Cool Thanks OOObe This did the trick for me,
Copy code
const data = await ListOfItemsTable.findRecords({})
const recordIDs = data.map((record) => record.id)
await ListOfItemsTable.deleteRecords(recordIDs)
still think the doc is wrong though....
Ah problem with the above code is it only deletes the first page (20 records of table rows) so for a table with 60 rows it has to be run 3x. So I have to set a limit:
Copy code
const limit = 1000
const data = await ListOfItemsTable.findRecords({
  limit: limit,
})
const recordIDs = data.map((record) => record.id)
await ListOfItemsTable.deleteRecords(recordIDs)
w
Okay thanks for the update 👍
10 Views