Skip to content

Instantly share code, notes, and snippets.

@taterbase
Created November 5, 2013 14:15
Show Gist options
  • Save taterbase/7319641 to your computer and use it in GitHub Desktop.
Save taterbase/7319641 to your computer and use it in GitHub Desktop.
mongoose = require 'mongoose'
Model = mongoose.Model
Query = mongoose.Query
setHooks = (hooks) ->
modifyCallback = ->
args = Array.prototype.slice.call arguments
args.forEach (arg, index) ->
if typeof arg is 'function'
oldCb = arg
return args[index] = (err, results) ->
return oldCb err if err
addHook = (index, err, data) ->
if err then return oldCb err
if not hooks[index] then return oldCb err, data
hooks[index] data, addHook.bind null, index + 1
addHook 0, err, results
return args
createFind = (hooks) ->
modifiedFind = ->
args = hooks.apply null, arguments
result = Model.find.apply @, args
result.exec = createExec hooks
result
createFindOne = (hooks) ->
modifiedFindOne = ->
args = hooks.apply null, arguments
result = Model.findOne.apply @, args
result.exec = createExec hooks
result
createExec = (hooks) ->
modifiedExec = ->
args = hooks.apply null, arguments
Query.prototype.exec.apply @, args
module.exports = (schema, hooks) ->
if not hooks then return
hooks = [hooks] if not Array.isArray hooks
hooks = setHooks hooks
schema.statics.find = createFind hooks
schema.statics.findOne = createFindOne hooks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment