forked from nvdnkpr/mongoose-faucet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.coffee
51 lines (38 loc) · 1.08 KB
/
index.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
async = require 'async'
module.exports = (model, query, itrFunc, options, cb) ->
if typeof options == "function"
cb = options
options = {}
options.snapshot ||= true
options.lean ||= false
options.select ||= false
stream = model.find(query).select(options.select).snapshot(options.snapshot).lean(options.lean).stream()
if options.batch
batch = []
addToBatch = (item, callback) ->
batch.push item
if batch.length is options.batch
completeBatch = batch
batch = []
itrFunc completeBatch, callback
else
callback()
queue = async.queue addToBatch, options.concurrency or 100
else
queue = async.queue itrFunc, options.concurrency or 100
queue.saturated = -> stream.pause()
queue.empty = -> stream.resume()
stream.on 'data', (doc) ->
queue.push doc
stream.on 'error', cb
stream.on 'close', ->
stream.resume()
done = () ->
if options.batch and batch.length != 0
itrFunc batch, cb
else
cb()
if queue.idle()
return done()
queue.drain = ->
done()