1

I have a company that contains products:

class Company
  include Mongoid::Document
  include Mongoid::Timestamps

  embeds_many :products

  index({"products.code" => 1}, {sparse: true, unique: true})

end

But when I create products(in the same parent) with the same code, like '123', the index does not check the uniqueness of it and it gets created normally. What is wrong?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Jirico
  • 1,242
  • 1
  • 15
  • 29

1 Answers1

3

Unique indexes are not enforced in embedded documents. There's an open issue on this.

Also, check this page for some workarounds/approaches to enforce this.

Anand Jayabalan
  • 12,294
  • 5
  • 41
  • 52
  • 1
    So, the index will work in queries, just the uniqueness checking will not work? I solved this just putting in the product model: validates_uniqueness_of :code, allow_blank: true. But it will make an extra query and I need to know if the index will work. – Jirico Mar 17 '14 at 21:47
  • 1
    Yes, the index will work. Just the uniqueness is not enforced. – Anand Jayabalan Mar 17 '14 at 21:49