Unique_constraint ecto mongodb not working

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

    timestamps()
 end

and this changeset:

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

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"})
      Repo.insert!(cs)

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

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 ?
Regards

1 Like

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:

1 Like

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

2 Likes

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

1 Like

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 ?

1 Like

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:

1 Like

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

2 Likes