Skip to content
30 changes: 30 additions & 0 deletions lib/mongoid/findable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,36 @@ def exists?(id_or_conditions = :none)
with_default_scope.exists?(id_or_conditions)
end

# Return true if any documents exist in the criteria.
#
# @example Determine if any documents exist
# Model.any?
#
# @return [ true | false ] If any documents exist.
def any?()
limit(1).count > 0
end

# Return true if only one document exists in the criteria.
#
# @example Determine if only one document exists
# Model.one?
#
# @return [ true | false ] If only one document exists.
def one?()
limit(2).count == 1
end

# Return true if more than one document exists in the criteria.
#
# @example Determine if many documents exist
# Model.many?
#
# @return [ true | false ] If many documents exist.
def many?()
limit(2).count > 1
end

# Finds a +Document+ or multiple documents by their _id values.
#
# If a single non-Array argument is given, this argument is interpreted
Expand Down
78 changes: 78 additions & 0 deletions spec/mongoid/findable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,84 @@
end
end

describe "#any?" do
context "when called on collection with documents" do
before do
Band.create!(name: "Tool")
end

it "returns true" do
expect(Band.any?).to be true
end
end

context "when called on collection with no documents" do

it "returns false" do
expect(Band.any?).to be false
end
end
end

describe "#one?" do
context "when called on collection with no documents" do
it "returns false" do
expect(Band.one?).to be false
end
end

context "when called on collection with one document" do
before do
Band.create!(name: "Radiohead")
end

it "returns true" do
expect(Band.one?).to be true
end
end

context "when called on collection with multiple documents" do
before do
Band.create!(name: "Tool")
Band.create!(name: "Radiohead")
end

it "returns false" do
expect(Band.one?).to be false
end
end

end

describe "#many?" do
context "when called on collection with no documents" do
it "returns false" do
expect(Band.many?).to be false
end
end

context "when called on collection with one document" do
before do
Band.create!(name: "Radiohead")
end

it "returns false" do
expect(Band.many?).to be false
end
end

context "when called on collection with multiple documents" do
before do
Band.create!(name: "Radiohead")
Band.create!(name: "Tool")
end

it "returns true" do
expect(Band.many?).to be true
end
end
end

describe "find_by!" do

context "when the document is found" do
Expand Down
Loading