Delete All or Specific Records in a Collection
Learn how to delete all data or only specific data directly from a collection using Corvid (a.k.a. Wix Code).
This example shows you how to delete shape records from a collection called #Shapes. Try the example below.
#btnDeleteAll
Try it!
#iptShape
#txtMessage
Select a shape to delete from the collection, or select delete all.
#btnDelete
Shape | Colour |
---|---|
Circle | Red |
Rectangle | Green |
Circle | Blue |
Square | Green |
Triangle | Red |
Circle | Blue |
Square | Green |
Triangle | Red |
Triangle | Blue |
Circle | Blue |
Triangle | Green |
Square | Red |
Circle | Red |
Circle | Red |
Square | Green |
Triangle | Red |
Triangle | Blue |
Circle | Blue |
Triangle | Green |
Square | Red |
Circle | Red |
Circle | Red |
Triangle | Red |
Triangle | Blue |
Circle | Blue |
Triangle | Green |
Circle | Red |
Circle | Blue |
Rectangle | Green |
Triangle | Red |
Square | Green |
Square | Green |
Triangle | Red |
Rectangle | Green |
Circle | Blue |
Add onChange event listeners to the #iptShape dropdown box. It will check that a shape has been selected before enabling the #btnDelete button. Add an onClick event listener to #btnDelete button to query and delete the selected shape records from the #Shapes collection. The #txtMessage text displays whether the delete operation has occurred.
Removing the eq shape condition from the wixData.query function will cause the btnDelete_click function to delete all records within #Shapes, not simply those which match the selected shape. Note that the delete permissions need to allow for the permissions of user which will be executing this code.
Page Code
A deleteData function is created in the Backend Code, which uses a wixData library function called truncate with a supressAuth parameter set to true - allowing anyone to delete data from the collection. Then the deleteData function can be imported to any Page Code and passed the collection/dataset name to delete i.e. truncate. Truncation deletes all the data in a dataset, but not the dataset itself.
Note that the truncate function also clears multiple-item reference fields in collections referenced by the specified collection. For example, suppose you have a Movies collection with an Actors field that contains multiple references to items in a People collection. Truncating the Movies collection also clears the data in the corresponding multiple-item reference field in the People collection.
Backend Code
Page Code