Reputation: 248
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
Upvotes: 17
Views: 19104
Reputation: 5891
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.
Upvotes: 26
Reputation: 1169
To generate uuid
in mongo db shell as a string, you need to call uuid()
the following way. First import uuid/v4
library using require statement (require statement will work on mongo shell as well).
const uuid = require('uuid/v4');
print(uuid());
// output : "df5679ea-34bf-48c0-9e9c-8c92686a7f56"
db.users.insert({name: "username", uuid: uuid()});
Upvotes: -3
Reputation: 214
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")
.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.Upvotes: 12