Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a mongdb UUID() to a string?

Tags:

uuid

mongodb

I want to generate a random UUID String, and insert it into mongo collection. How can I do it? I do not want a hex. I need the dashes. I tried UUID().toString(), and it does not seem to work

like image 508
ProgrammerNeo Avatar asked Jul 19 '19 22:07

ProgrammerNeo


2 Answers

According to your own comment, UUID().toString() includes the method name. Your solution includes the quotation marks. To get rid of those, you could use the following:

UUID().toString().split('"')[1]

Explanation:

  • UUID().toString() will give a string containing UUID("00000000-0000-0000-0000-00000000000").
  • The split('"') will split the string, dividing by the quotation marks, into an array, which is ['UUID(', '00000000-0000-0000-0000-000000000000', ')'].
  • [1] selects the second element from that array, which is your UUID as a string.
like image 66
Jeroen van Montfort Avatar answered Oct 14 '22 17:10

Jeroen van Montfort


The only way I was able to make this work was to use

UUID()
  .toString('hex')
  .replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5')

because I get UUID().hex is not a function error when I try UUID().hex() and UUID().toString() only returns gibberish.

like image 5
crackmigg Avatar answered Oct 14 '22 17:10

crackmigg