Naman
Naman

Reputation: 31878

Convert UUID to String for insert in mongodb

Upon trying the following code:

db.getCollection('col').find({}).forEach(function(doc){
            var id = new UUID().toString(); // this doesn't work, neither does 'var id = new UUID();'
            db.getCollection('pubCol')
                .update({
                    "uuid" : id,
                    "deleted" : false
                    }
            , {upsert: true});
         });

I end up getting the following results respectively

"uuid" : "UUID(\"4554a991-2b7f-4464-b871-5f4e91332630\")"
"uuid" : UUID("4554a991-2b7f-4464-b871-5f4e91332630")

But I am looking for

"uuid" : "4554a991-2b7f-4464-b871-5f4e91332630"

Upvotes: 3

Views: 3470

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

UUID().hex() returns the string you are after but without hyphens.

You can split it manually, e.g. with regexp:

UUID().hex().match(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/).slice(1,6).join('-')

Upvotes: 6

Related Questions