Skip to content

Commit

Permalink
Fix findRandom when selector does not match any documents.
Browse files Browse the repository at this point in the history
  • Loading branch information
fehmicansaglam committed Jul 15, 2014
1 parent a1fe9e4 commit 3a4dab9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion bson/src/main/scala/dao/BsonDao.scala
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ abstract class BsonDao[Model, ID](db: () => DB, collectionName: String)(implicit
def findRandom(selector: BSONDocument = BSONDocument.empty): Future[Option[Model]] = {
for {
count <- count(selector)
index = Random.nextInt(count)
index = if (count == 0) 0 else Random.nextInt(count)
random <- collection.find(selector).options(QueryOpts(skipN = index, batchSizeN = 1)).one[Model]
} yield random
}
Expand Down
13 changes: 13 additions & 0 deletions bson/src/test/scala/dao/DummyBsonDaoSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,19 @@ class DummyBsonDaoSpec
}
}

it should "return None when findRandom does not match any documents" in {
val dummyModel = DummyModel(name = "foo", surname = "bar", age = 32)

val futureResult = for {
insertCount <- dao.insert(dummyModel)
random <- dao.findRandom("age" $gt 50 $lt 60)
} yield random

whenReady(futureResult) { random =>
random should be('empty)
}
}

it should "find all of the selected documents" in {
val dummyModels = DummyModel.random(100)

Expand Down

0 comments on commit 3a4dab9

Please sign in to comment.