How to remove doc that don't _id field?

I would like to remove doc with field that don’t _id field.

CollectionName.remove({otherField: "hi"});

but don’t work, and show

errorClass {error: 403, reason: "Not permitted. Untrusted code may only remove documents by ID.", details: undefined, message: "Not permitted. Untrusted code may only remove documents by ID. [403]", errorType: "Meteor.Error"…}details: undefinederror: 403errorType: "Meteor.Error"message: "Not permitted. Untrusted code may only remove documents by ID. [403]"reason: "Not permitted. Untrusted code may only remove documents by ID."stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Middle

Two ways:

1. From the client only:

CollectionName.find({otherField: "hi"}).forEach(function (doc) {
  CollectionName.remove({_id: doc._id});
});

OR

2. Client and server:

CLIENT:

Meteor.call('removeUsingOtherField', "hi");

SERVER (or BOTH):

Meteor.methods({
  "removeUsingOtherField" : function (value) {
    CollectionName.remove({otherField: value}, {multi: true});
  }
})

(Note: value will be “hi” in this case)

1 Like

Very thanks for your reply, but in Meteor docs say the same syntax for client and server.
I don’t understand.

Ah yes… that’s true. This is one of the rare exceptions. It’s a security feature. Updates from the client can only be by _id to avoid inadvertent mass destruction of docs in the database [EDIT: nope, not the real reason – it’s more to do with being able to learn about things about the database that should remain undisclosed – thanks @Peppe_LG].

The method "removeUsingOtherField" in my example runs on both client and server if you define it in a file that’s shared by both. On the client, the documents in the client cache (a subset of your mongo docs) are updated immediately and the results are reactively displayed. In the meantime, there is a round trip to the server happening, where the same method runs on the server and updates actual mongodb docs. The results of this action make their way back to the client via the pub/sub set up and, unless the server results differed from the client update results, that’s the end of the story. If the server update was rejected for some reason, things are changed back in the client cache so that the client cache matches the actual mongodb docs again.

These are hard concepts to get your head around at first but so, so awesome when you really get going with Meteor.

The main reason is to avoid data leakage. See https://github.com/meteor/meteor/issues/3775#issuecomment-75315579

I stand corrected. Thanks @Peppe_LG.