target.collection = (name) ->
throw new Error('Not yet connected to mongo') if target._mongo?.whenConnected.isPending()
@_mongo.db.collection name
_wrappedMethods = [ 'insert', 'remove', 'rename', 'save', 'update', 'count', 'drop', 'findOne',
'createIndex', 'ensureIndex', 'dropIndex', 'reIndex', 'group', 'options', 'indexes', 'stats',
'findAndModify', 'findAndRemove' ]
_wrapMethod = (target, name) ->
target[name] = (args...) ->
throw new Error 'Collection is not set. Use .useCollection before using this wrapper' if !@_mongo.collection?
throw new Error "Method .#{name}Async() does not exist in collection." if !@_mongo.collection[name + 'Async']
@_mongo.collection[name + 'Async'].apply(@_mongo.collection, args)
_wrapFind = (target) ->
target.find = (args...) ->
throw new Error 'Collection is not set. Use .useCollection before using this wrapper' if !@_mongo.collection?
throw new Error "Method .find() does not exist in collection." if !@_mongo.collection.find
@_mongo.collection.find.apply(@_mongo.collection, args).stream()
_deferCollectionMethod = (collection, name, target) ->
collection[name] = (args...)->
target._mongo.whenConnected.then ->
throw new Error "Method .#{name} does not exist in collection." if !target._mongo.collection[name]
target._mongo.collection[name].apply(target._mongo.collection, args)
_deferFind = (collection, target) ->
collection.find = (args...) ->
result = new PassThrough
objectMode: true
highWaterMark: 10
target._mongo.whenConnected.then ->
target._mongo.collection.find.apply(target._mongo.collection, args).stream().pipe result
{ stream: -> result }