How to create a button to erase database

Hello

Is it possible to create a button that will completely erase a database, please?

Hi Karl,

You could use the truncate function within an onClick event of a button.

I will try. Thanks

Yes it’s possible, here’s how.

  1. Import wixData , put it on the top of the code page.
import wixData from 'wix-data';
  1. Create an .onClick( ) event handler on the button that you want it do the this job by clicking on the (+) button next to the onClick event in the button’s properties panel.
export function button1_click(event) {
//Add your code for this event here:
}

  1. Query the database that you want to erase all of its content. Make sure to use the following code inside the event handler that you’ve created in step 2.
wixData.query("collectionName")
.find()
.then( (results) => {
    let items = results.items  
    // Next code will be here
})
  1. Now we’ll use a for loop to make the code run for every element.
for (let i = 0; i < items.length; i++) {
    let item  = items[i];
    wixData.remove("collectionName", item);
}

And that’s it, you may need to change some identifiers to let the code runs for you.

  1. collectionName - change it to your collection name.
  2. button1 - Whatever button you created the onClick( ) event on.

Here is the complete code:

import wixData from 'wix-data';

export function button1_click(event) {
//Add your code for this event here:
    wixData.query("collectionName")
    .find()
    .then( (results) => {
        let items = results.items;
        
        for (let i = 0; i < items.length; i++) {
            let item  = items[i];
            wixData.remove("collectionName", item);
        }
    })
}

I didn’t tested out though, test it and and tell me if it worked.
Everything you need to change is marked in blue

Happy Coding :blush:
Ahmad.