Skip to content

Commit

Permalink
Count the values of an index property
Browse files Browse the repository at this point in the history
  • Loading branch information
wdavidw committed Mar 13, 2012
1 parent 2a4febd commit 9230c2b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
22 changes: 18 additions & 4 deletions lib/Records.coffee
Expand Up @@ -133,13 +133,27 @@ module.exports = class Records extends Schema
-----------------
Count the number of records present in the database.
`count(property, value, callback)`
----------------------------------
Count the number of values for an indexed property.
###
count: (callback) ->
{redis} = @
{db, name, identifier} = @data
@redis.scard "#{db}:#{name}_#{identifier}", (err, count) ->
return callback err if err
callback null, count
{db, name, identifier, index} = @data
if arguments.length is 3
property = callback
value = 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) ->
return callback err if err
callback null, count
else
@redis.scard "#{db}:#{name}_#{identifier}", (err, count) ->
return callback err if err
callback null, count
###
`create(records, [options], callback)`
Expand Down
22 changes: 21 additions & 1 deletion test/count.coffee
Expand Up @@ -35,4 +35,24 @@ describe 'count', ->
Users.count (err, count) ->
should.not.exist err
count.should.eql 2
next()
next()

it 'should count the index elements of a property', (next) ->
Users.create [
username: 'username_1',
email: 'my@email.com',
password: 'my_password'
,
username: 'username_2',
email: 'my_2@email.com',
password: 'my_password'
,
username: 'username_3',
email: 'my@email.com',
password: 'my_password'
], (err, user) ->
Users.count 'email', 'my@email.com', (err, count) ->
should.not.exist err
count.should.eql 2
next()

0 comments on commit 9230c2b

Please sign in to comment.