Inconsistent mongo/postgres unique constraint behavior
See original GitHub issueBug report
I have a model:
keystone.createList('Organization', {
phone: {
type: Text,
isUnique: true,
},
...
})
- Mongo: it means that I have only one record with a
null
phone. - Postgres: it means that I can have multiple records with a
null
phone.
CI tests fail with:
[
{
message: 'E11000 duplicate key error collection: main.users index: phone_1 dup key: { phone: null }',
locations: [ { line: 2, column: 3 } ],
path: [ 'user' ],
extensions: {
code: 'INTERNAL_SERVER_ERROR',
exception: {
driver: true,
name: 'MongoError',
index: 0,
code: 11000,
keyPattern: { phone: 1 },
keyValue: { phone: null },
errmsg: 'E11000 duplicate key error collection: main.users index: phone_1 dup key: { phone: null }',
How-to solve
Use sparse index for MongoDB: more info here: https://stackoverflow.com/a/24430345
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (6 by maintainers)
Top Results From Across the Web
Inconsistent mongo/postgres unique constraint behavior #3114
Postgres: it means that I can have multiple records with a null phone. CI tests fail with: [ { message: 'E11000 duplicate key...
Read more >Why does Postgres handle NULLs inconsistently where ...
NULL is considered to be unique because NULL doesn't represent the absence of a value. A NULL in a column is an unknown...
Read more >Inconsistent equality checking of Unicode text in Postgres 9.5?
A unique constraint is considering some strings equal that GROUP BY is considering different.
Read more >Unique constraint violation in Postgres due to OS upgrade
After upgrade from Debian Stretch (PostgreSQL 9.6) to Debian Buster (PostgreSQL 11) there were duplicated data in the database table with unique constraint...
Read more >PostgreSQL unique constraint null: Allowing only one Null - EDB
First, let me show the default Postgres behavior: CREATE TABLE nulltest (x INTEGER UNIQUE); INSERT INTO nulltest VALUES (NULL); INSERT INTO ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I think it’s better to drop
unique
field options and move it toknexOptions
andmongooseOptions
. If you don’t want to homogenise Mongo/Postgres behavior.It’s unexpected for me. And I can’t write Keystone modules for Mongo and Postgres. I should choose one!
Thank you @pahaz !! I was able to get this to work using the following:
phoneNumber: { type: Text, isUnique: true, isRequired: false, mongooseOptions: { sparse: true } },