node.jscollectionssails.jswaterlinesails-mongo

sails.js remove all members from collection waterline


I want to remove all members that a collection has , but I do not want to pass every member ID to .member() method . waterline documentation explain a way to delete specific members like :

await User.removeFromCollection(3, 'pets')
.members([99,98]);

I want to have sth like :

await User.removeFromCollection(3, 'pets')
.members(['*']);

Solution

  • As far as I can tell, this should be done using .destroy() without a criteria.

    Edit (2019-07-10): Added the empty curlies as per the comment from noobular

    await User.destroy({});                // Removes all records from your User collection
    
    await User.destroy({name:'Bill'};    // Removes all records from your User collection
                                            where the 'name' is 'Bill'
    

    Docs: .destroy()

    Update

    After you pointed out I misread your question, I came up with this solution. The docs for .removeFromCollection() states that passing in an array of parent ID's will remove all children in the specified collection, but this does not seem to function as written.

    I did however find a working solution for you using .replaceCollection().

    await User.replaceCollection(3, 'pets', []);
    
    OR
    
    await User.replaceCollection(3, 'pets').members([]);
    

    Passing in an empty array will replace the current array of associations with the empty array, clearing out the current associations.

    Docs: .replaceCollection()