New Package pmogollons:collection-hooks

pmogollons:collection-hooks extends Mongo.Collection in Meteor with useful hooks like onInsert, onBeforeInsert, onUpdate, and onRemove, allowing you to execute custom code on these operations.

Key Benefits:

  • Safely modify documents in hooks without affecting the main operation.
  • onBeforeInsert hook is async and changes to the doc are passed to the insert op
  • Supports direct access by bypassing hooks when necessary.
  • Hooks are only available on the server, ensuring security and control.
  • Simpler implementation that is easy to understand, using event emitter.
  • Ability to set the projection of the underlying queries
  • Compatible with pmogollons:nova to fetch docs with links

Quick Example:

Collection.onInsert(function ({ userId, doc }) {
    // Code here runs after insert operation
}, { docFields: { field1: 1, field2: 1 } });

Why not use meteor-collection-hooks
Well, meteor-collection-hooks has a very different approach than this package. If you need before hooks, find and findOne hooks, you should stick with meteor-collection-hooks. We wanted to start fresh, with server only hooks, no before hooks appart from onBeforeInsert, simpler and easier to mantain codebase, and is only compatible with meteor v3+.

Check the GitHub repository if you want to know more.


If you guys have any ideas let me know bellow or on discord @paulomogollon

4 Likes

Very nice! Can I define multiple onInsert functions for a collection and will all of them be run? This is especially important for packages and that for example do changes around Meteor.user.

It does run multiple hooks, every hook except from onBeforeInsert will run multiple if defined.

After hooks are just event listeners that run independently from each other, so if one throws the others wont be affected. And errors can be catched with CollectionHooks.onError listener to send them to monti or how ever you want to handle them.

onBeforeInsertwill not run multiple hooks because what we do is to extend the insertAsync method of Collection to run the hook before the operation. It probably will not be hard to implement, but im not sure I like the idea of multiple onBeforeInsert hooks.

Also it does work correctly with Meteor.users ops.

Version 1.0.3 released

What’s new

  • Multiple onBeforeHooks can be defined (will run in sequense)
  • Fixed issue with userId outside of method context
  • docFields is extended for all hooks
  • Improvements to error handling
  • Now hooks return hookRemove function
4 Likes