sails: Unable to use UUID as primary key
Sails version: v1.0.0-36 Node version: any NPM version: any Operating system: any
Sails v1.x.x requires that id (or whatever the primary key is) is either set to required or autoIncrement. This makes it difficult (impossible?) to use a uuid (uuid.v4()) as the primary key.
In v0.12.x, either of these would work:
autoPK: false,
attributes: {
id: {
type: 'string',
primaryKey: true,
defaultsTo: function() {
return uuid.v4();
}
}
}
or
autoPK: false,
attributes: {
id: {
type: 'string',
primaryKey: true
}
},
beforeCreate: function(values, cb) {
values.id = uuid.v4();
cb();
}
In v1.x.x, neither of the above work. Is there another way to use a uuid as the primary key?
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 17 (3 by maintainers)
Thanks @toni-ismail . Currently i am generating the UUID on controller side and using that as primary key in model with the following config. it’s seem working fine for me. Anyway i will give a try with your idea.
Does the Sails project have more than 5 Years and there is still no functionality to generate UUID for IDs? Somewhere there must be some documentation for such a thing.
@deeyonn Please can you share with me the code of how you have done this in the blueprint?
hi, is there an update/solution to make blueprint model attribute’s id to default to uuid v4?
What i want to do is to overwrite all models in config/models.js to have id assigned a varchar(36) uuid v4
EDIT: I used sails parseBlueprintOptions to set id = uuid for every create action
That’s true. Even if the trick is easy it requires attention:
Hi @umarfarook882 , @fenichelar ,
I’m sorry for the late comment, I just want to show how to setup model to use UUID with ‘sails-postgresql’.
on your postgree database, you need to create new extension :
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";on config/model.js :
you should setting migrate to ‘drop’ or ‘safe’ if you setting to ‘alter’ you will get an error message.
You can find that ways on sails-postgresql code here https://github.com/balderdashy/sails-postgresql/blob/881275fc999e680f517eb4dccbc99a7bb3dbe1ce/helpers/private/schema/build-schema.js#L51
Hopes it can helps anyone who want to use UUID on their primary key. Thanks.
@fenichelar When you use the automatic blueprint, you’re still setting some attributes, right? You should be able to set
idas one of those. You’ll just need to generate your UUID on the front end.