Unique_constraint ecto mongodb not working

Tags: #<Tag:0x00007f1142469c18> #<Tag:0x00007f1142469a88>


Hello all.

I have this simple struct:

schema "domains" do
    field :name, :string
    field :redirect, :string

    field :name_checked, :boolean, default: false
    field :redirect_checked, :boolean, default: false


and this changeset:

def changeset(domain, params \\ %{}) do
    |> cast(params, [:name, :redirect, :name_checked, :redirect_checked])
    |> unique_constraint(:name) # this is not working :(
    |> validate_required([:name, :redirect])

However when testing the unique constraint on the name, it doesn’t work, here is my test:

test "uniqueness of name" do
      url = "http://domain.com"
      cs = Domain.changeset(%Domain{}, %{name: url, redirect: "http://redirect.com"})

      cs2 = Domain.changeset(%Domain{}, %{name: url, redirect: "http://redirect2.com"})
      assert {:error, changeset} = Repo.insert(cs2)

This test should pass as the second insert should match {:error, changeset}, however, the second insert pass without raising the unique_constraint

I’m using ecto 2 with the ecto-2 branch here: https://github.com/michalmuskala/mongodb_ecto/tree/ecto-2

Anything I’m missing ?


The validation is done in the DB, and you did not show your migration file for that table, so what is your migration file? :slight_smile:


Yup, I think you need to declare a unique index on Mongo or something.


Thank you but there is no migration file in mongodb :slight_smile: I think I need to play directly with indexes in mongodb.


Thank you Jose I will take a look but in this case, mongodb will ensure the uniqueness so do I still need the unique_constraint in my changeset ?


Well ‘how’ does it ensure uniqueness? If it tells you via an error then the unique_constraint will catch it,thus it would be needed, just need to make sure that mongodb has a unique index set there. :slight_smile:


Ok I see, I will test it tomorrow but pretty sure it will work. Need to get rid of my rails habits !! Cheers !!