'How can I convert a mongdb UUID() to a string?
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
Solution 1:[1]
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 containingUUID("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.
Solution 2:[2]
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.
Solution 3:[3]
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()});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeroen van Montfort |
| Solution 2 | crackmigg |
| Solution 3 | PARAMANANDA PRADHAN |
