meteor-collection-hooks icon indicating copy to clipboard operation
meteor-collection-hooks copied to clipboard

FR: Ability to add a hook to all collections

Open lorensr opened this issue 10 years ago • 6 comments
trafficstars

Something like

CollectionHooks.after.remove: function (userId, doc) {
  // ...
});

that runs after a doc is removed from any collection. Use case:

http://stackoverflow.com/questions/29638910/how-can-you-log-all-mongo-write-commands

lorensr avatar Apr 15 '15 08:04 lorensr

I like it. I'll keep this open and I think this will eventually make it in when I have some time

matb33 avatar Apr 22 '15 18:04 matb33

Nice, thanks! See second answer for how to get a list of all collections:

http://stackoverflow.com/questions/10984030/get-meteor-collection-by-name

lorensr avatar May 06 '15 10:05 lorensr

That second answer is not going to work consistently... A collection can be instantiated anywhere, not just the global scope... That's a poor approach...

But anyway, it's irrelevant as we just leverage the prototype for this stuff

matb33 avatar May 06 '15 20:05 matb33

can i do this with default options ?

CollectionHooks.defaults.before.insert = {createdAt: new Date()};

CollectionHooks.before.insert (userId, doc) ->
    _.extend doc,
        createdAt: new Date()

crapthings avatar Jul 07 '15 12:07 crapthings

+1

Any plans of implementing this?

Thanks for making the package public!

[UPDATE] I've implemented this using a superclass on my Collections. Any thoughts on how this might be a good/bad idea while we wait for this feature?

leite08 avatar Jan 16 '18 14:01 leite08

To be honest I don't believe that the approach this package takes, is a good one any longer.

Subclassing Mongo.Collection would be "better", but even better in my world would be to have a functional api like the following.

import addHook from "meteor/zimme:collection-hooks";

const handle = addHook("after", "insert", Posts, function() { console.log("Runs after insert"); });

// Posts now have an after insert callback

handle.remove()

// Posts doesn't have an after insert callback

This way you don't add needless utility functions to Mongo.Collection. More like the api I've used in https://github.com/meteor-collectionbehaviours/timestamp

I do believe the current api was chosen in the hopes of it getting merged into core some day.

zimme avatar Jan 16 '18 14:01 zimme