Search code examples
strapi

How can I define and use a UUID field?


I need a UUID field in a content type, with the help of the introduction below I have modified the file "MyType.settings.json".

https://strapi.io/documentation/3.x.x/guides/models.html#define-the-attributes

"uid": {
  "default": "",
  "type": "uuid"
},

I thought a UUID is automatically saved, but nothing happens.

How can I define and use a UUID field? Can someone give me a hint? Should I also modify the file \api\MyType\controllers\MyType.js?

Thanks in advance!

Benjamin


Solution

  • You will have to use uuid node module. So keep your attribute and in the lifeCyle functions, set your uuid with the lib.

    'use strict';
    
    const uuid = require('uuid');
    
    module.exports = {
      beforeCreate: async (model) => {
        model.set('uid', uuid());
      }
    };