Back to Sails

`.destroy()`

docs/reference/waterline/models/destroy.md

12.12.20003.8 KB
Original Source

.destroy()

Destroy records in your database that match the given criteria.

usage
await Something.destroy(criteria);

or

  • var destroyedRecords = await Something.destroy(criteria).fetch();

Usage

ArgumentTypeDetails
1criteria((dictionary))Records matching this Waterline criteria will be destroyed. Be warned, if you specify an empty dictionary ({}) as your criteria, all records will be destroyed! destroy queries do not support pagination using skip and limit or projections using select.
Result
TypeDescription
((array?)) of ((dictionary))The destroyed records are not provided as a result by default in order to optimize for performance. To override the default setting, chain .fetch() and the newly destroyed records will be sent back. (Be aware that this requires an extra database query in some adapters.)
Errors
NameTypeWhen?
UsageError((Error))Thrown if something invalid was passed in.
AdapterError((Error))Thrown if something went wrong in the database adapter.
Error((Error))Thrown if anything else unexpected happens.

See Concepts > Models and ORM > Errors for examples of negotiating errors in Sails and Waterline.

Meta keys
KeyTypeDetails
fetch((boolean))If set to true, then the array of destroyed records will be sent back.

Defaults to false.

For more information on meta keys, see .meta().

Example

To delete any users named Finn from the database:

javascript
await User.destroy({name:'Finn'});

sails.log('Any users named Finn have now been deleted, if there were any.');

To delete two particular users who have been causing trouble:

javascript
await User.destroy({
  id: { in: [ 3, 97 ] }
});

sails.log('The records for troublesome users (3 and 97) have been deleted, if they still existed.');
Fetching destroyed records

To delete a particular book and fetch the destroyed record, use .destroyOne().

To delete multiple books and fetch all destroyed records:

javascript
var burnedBooks = await Book.destroy({
  controversiality: { '>': 0.9 }
}).fetch();
sails.log('Deleted books:', burnedBooks);

Notes

  • This method can be used with await, promise chaining, or traditional Node callbacks.
  • If you want to confirm that one or more records exist before destroying them, you should first perform a find(). However, it is generally a good idea to try to do things rather than checking first, lest you end up with a race condition.
<docmeta name="displayName" value=".destroy()"> <docmeta name="pageType" value="method">