Postgresql duplicate key value violates unique constraint

297 views
Skip to first unread message

Davy Braun

unread,
Jun 29, 2015, 3:38:27 AM6/29/15
to loopb...@googlegroups.com
Bumping this in a new thread because it's still an issue and it's blocking my progress big time. I really like the framework and was willing to push the usage of Strongloop's suite of tools despite the quirks in Loopback for a project I'm leading for my time but I'll have to put it on hold I guess....

In a previous post (https://groups.google.com/forum/#!topic/loopbackjs/cfvHRS0OAOc) I mentioned an error when trying to insert new models inside the DB via REST.
It occurs when the DB has previously been filled with some models.

{
 
"error": {
   
"name": "error",
   
"status": 500,
   
"message": "duplicate key value violates unique constraint \"collection_pkey\"",
   
"length": 188,
   
"severity": "ERROR",
   
"code": "23505",
   
"detail": "Key (id)=(6) already exists.",
   
"schema": "public",
   
"table": "collection",
   
"constraint": "collection_pkey",
   
"file": "nbtinsert.c",
   
"line": "398",
   
"routine": "_bt_check_unique",
   
"stack": "error: duplicate key value violates unique constraint \"collection_pkey\"\n    at Connection.parseE (/Users/dpb/Code/Apps/mypleasu.re/coop/node_modules/loopback-connector-postgresql/node_modules/pg/lib/connection.js:534:11)\n    at Connection.parseMessage (/Users/dpb/Code/Apps/mypleasu.re/coop/node_modules/loopback-connector-postgresql/node_modules/pg/lib/connection.js:361:17)\n    at Socket.<anonymous> (/Users/dpb/Code/Apps/mypleasu.re/coop/node_modules/loopback-connector-postgresql/node_modules/pg/lib/connection.js:105:22)\n    at Socket.emit (events.js:107:17)\n    at readableAddChunk (_stream_readable.js:163:16)\n    at Socket.Readable.push (_stream_readable.js:126:10)\n    at TCP.onread (net.js:538:20)\n    at TCP.onread (/Users/dpb/Code/Apps/mypleasu.re/coop/node_modules/loopback/node_modules/continuation-local-storage/node_modules/async-listener/glue.js:188:31)"
 
}

}


It first happened when trying to POST via a hasMany relationship (i.e. POST /api/collections/1/videos/ ).
As Raymond suggested, I checked (and caught, and removed on the fly) an ID that was inserted in the application layer, before the DB was touched, using an operation hook (before save)... 
But this little hack doesn't work in other cases (i.e. POST /api/collections/). I can't see any ID being inserted in the application layer before save, and I don't know what is happening nor where to look.

Can somebody please help me out?

Thanks in advance.

Davy Braun

unread,
Jun 29, 2015, 6:40:03 AM6/29/15
to loopb...@googlegroups.com
Adding a new information after tests: the bug occurs when, on a blank database, you insert new values but setting the IDs explicitly in your models (i.e. for a set of fixtures).
Reply all
Reply to author
Forward
0 new messages