diff --git a/README.md b/README.md index 0b4b36f..4574d3b 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,9 @@ test.before.find(function (userId, selector, options) { }); ``` -__Important:__ This hook does not get called for `after.update` hooks (see https://github.com/Meteor-Community-Packages/meteor-collection-hooks/pull/297). +__Important:__ +- The function used as `before.find` hook cannot be async +- This hook does not get called for `after.update` hooks (see https://github.com/Meteor-Community-Packages/meteor-collection-hooks/pull/297). -------------------------------------------------------------------------------- diff --git a/find.js b/find.js index c680339..da5c04b 100644 --- a/find.js +++ b/find.js @@ -17,6 +17,8 @@ CollectionHooks.defineWrapper('find', function (userId, _super, instance, hooks, hooks.before.forEach(hook => { if (!hook.hook.constructor.name.includes('Async')) { hook.hook.call(this, userId, selector, options) + } else { + throw new Error('Cannot use async function as before.find hook') } }) @@ -27,13 +29,7 @@ CollectionHooks.defineWrapper('find', function (userId, _super, instance, hooks, if (cursor[method]) { const originalMethod = cursor[method] cursor[method] = async function (...args) { - // Apply asynchronous before hooks - for (const hook of hooks.before) { - if (hook.hook.constructor.name.includes('Async')) { - await hook.hook.call(this, userId, selector, options) - } - } - + // Do not try to apply asynchronous before hooks here because they act on the cursor which is already defined const result = await originalMethod.apply(this, args) // Apply after hooks diff --git a/tests/find.js b/tests/find.js index ea7e05f..bdca1c0 100644 --- a/tests/find.js +++ b/tests/find.js @@ -6,8 +6,9 @@ Tinytest.addAsync('find - selector should be {} when called without arguments', const collection = new Mongo.Collection(null) let findSelector = null - collection.before.find(async function (userId, selector, options) { + collection.before.find(function (userId, selector, options) { findSelector = selector + return true }) // hooks won't be triggered on find() alone, we must call fetchAsync() diff --git a/tests/find_after_hooks.js b/tests/find_after_hooks.js index 8292779..f960c0e 100644 --- a/tests/find_after_hooks.js +++ b/tests/find_after_hooks.js @@ -53,7 +53,7 @@ Tinytest.addAsync('issue #296 - after insert hook always finds all inserted', as test.equal(afterCalled, true) }) -Tinytest.addAsync('async find hook - after insert hook always finds all inserted', async function (test, next) { +Tinytest.addAsync('find hook - after insert hook always finds all inserted', async function (test, next) { const collection = new Mongo.Collection(null) collection.before.find((userId, selector) => {