将 UUID 转换为字符串以插入 mongodb

Convert UUID to String for insert in mongodb

尝试以下代码时:

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});
         });

我最终分别得到如下结果

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

但我正在寻找

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

UUID().hex() returns 您要查找的字符串,但没有连字符。

您可以手动拆分,例如使用正则表达式:

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