Browse files

Count multiple values at once

  • Loading branch information...
1 parent 9230c2b commit 4947bca8858b71e5e834ce1dd0045afc753a4da3 @wdavidw committed Mar 13, 2012
Showing with 33 additions and 8 deletions.
  1. +26 −7 lib/Records.coffee
  2. +7 −1 test/count.coffee
View
33 lib/Records.coffee
@@ -131,25 +131,44 @@ module.exports = class Records extends Schema
`count(callback)`
-----------------
- Count the number of records present in the database.
+ Count the number of records present in the database.
- `count(property, value, callback)`
+ Counting all the records:
+
+ Users.count, (err, count) ->
+ console.log 'count users', count
+
+ `count(property, values, callback)`
----------------------------------
- Count the number of values for an indexed property.
+ Count the number of one or more values for an indexed property.
+
+ Counting multiple values:
+
+ Users.get 'users', properties:
+ user_id: identifier: true
+ job: index: true
+ Users.count 'job' [ 'globtrotter', 'icemaker' ], (err, counts) ->
+ console.log 'count globtrotter', counts[0]
+ console.log 'count icemaker', counts[1]
###
count: (callback) ->
{redis} = @
{db, name, identifier, index} = @data
if arguments.length is 3
property = callback
- value = arguments[1]
+ values = arguments[1]
callback = arguments[2]
return callback new Error "Property is not indexed" unless index[property]
- value = @hash value
- @redis.scard "#{db}:#{name}_#{property}:#{value}", (err, count) ->
+ isArray = Array.isArray values
+ values = [values] unless isArray
+ multi = redis.multi()
+ for value, i in values
+ value = @hash value
+ multi.scard "#{db}:#{name}_#{property}:#{value}"
+ multi.exec (err, counts) ->
return callback err if err
- callback null, count
+ callback null, if isArray then counts else counts[0]
else
@redis.scard "#{db}:#{name}_#{identifier}", (err, count) ->
return callback err if err
View
8 test/count.coffee
@@ -51,8 +51,14 @@ describe 'count', ->
email: 'my@email.com',
password: 'my_password'
], (err, user) ->
+ # Count one value
Users.count 'email', 'my@email.com', (err, count) ->
should.not.exist err
count.should.eql 2
- next()
+ # Count multiple values
+ Users.count 'email', ['my@email.com', 'my_2@email.com'], (err, counts) ->
+ should.not.exist err
+ counts[0].should.eql 2
+ counts[1].should.eql 1
+ next()

0 comments on commit 4947bca

Please sign in to comment.