Deleting all documents from a collection from the web console


#1

How do I delete all documents from the web console?


#2

You can only update by records by _id from the client. Because of this, there are 2 ways to accomplish it,

1.) Create a server side meteor method that deletes the documents. You can call the method from the client console easily. Be careful, anyone who is a user can call this method, adjust as necessary.

You will also need to make sure you collection allows remove/delete permission when making the collection

// call this method, from console, passing the collection name as a String (required), 
// and optionally a filter object, such as { company: 'Acme Inc' } for example.


Meteor.call(deleteDocs, 'Clients', function(err, res) {
  if (err) console.log('err in deleteDocs', err);
  if (res) console.log('res in deleteDocs', res);
});

Meteor.methods({
  deleteDocs: function(collectionName, filter = {}) {
    check(collectionName, String);
    check(filter, Object);
    check(this.userId, String);
    this.unblock();

    const collection = global[collectionName];
    check(collection, Mongo.Collection);

    return collection.remove(filter);

  }
})

2.) if you are on the client, subscribed to the documents and you want to perform the delete on the client regardless then you can get the _ids in an array, then pass that as a filter.

// if collection name = Clients

// get a clean array of _ids to pass to the below mongo filter
const _idArray = _.map(Clients.find().fetch(), (doc) => {
  return doc._id;
})

if (_.isArray(_idArray) && _idArray.length) {
  Clients.remove({_id: {$in: _idArray}});
}
// if this doesn't work, then just iterate over _id like above _.map and call Clients.remove({_id: doc._id});


#3

I’m getting an internal server error when I call 1. Any ideas why I would get an internal server error?


#4

you can remove the various check()'s to see which one is failing, you also have to be logged in as a user, or remove that check, you have to pass the collection name as a String. Don’t try to pass it not as a string. Post your code and any errors if you need more help.

also, You may have instantiated the collection with: new Meteor.Collection. if that is the case, then change the Mongo.Collection to Meteor.Collection.


#5

inside Meteor.methods in server js file

what I called:
Meteor.call(‘deleteDocs’, ‘Collection’, function(err, res) {
if (err) console.log(‘err in deleteDocs’, err);
if (res) console.log(‘res in deleteDocs’, res);

My Error:
err in deleteDocs Object { stack: “Meteor.makeErrorType/errorClass@htt…”, error: 500, reason: “Internal server error”, details: undefined, message: “Internal server error [500]”, errorType: “Meteor.Error” }


#6

just remove all of the check() code in the method, you can also make a static method that doesn’t take parameters,

so just put Collection.remove({})

is your collection name really Collection?


#7

No it isn’t. I got my app working though. Thank you!