简体   繁体   中英

MongoDB insert UUID only using middleware?

i dont know how to insert UUID into MongoDB properly.
For example:

db.users.insert({ uuid: UUID(buffer) })

Buffer must be 32 hex string and MongoDB natively dont create UUID, only stores this? I'm right? But where i create the random UUID, eg through Node.js middleware i have a random UUID 11986aba-7c5a-4626-b354-80be23c25516 , so its a 36 length string and now i cant place it into UUID(buffer) . What i should doing with this UUID generated from node.js uuid module? And how later read this inserted values from MongoDB as a normal uuid string?

BSON, hence MongoDB support the UUID type. From the Mongo Shell, you can use the UUID() constructor to convert from a 32 hex-digits string to an UUID internal representation.

From node.js , using the node-uuid module you can easily generate v1 or v4 UUID and store them in a buffer object:

> my_uuid = uuid.v4(null, new Buffer(16))
<Buffer 91 ed c3 f0 20 36 4b f3 94 0c d3 d6 b0 a9 de 03>

You can then convert that to type 4 binary SUBTYPE_UUID (or the deprecated type 3 SUBTYPE_UUID_OLD ):

> collection.insert({uuid: mongodb.Binary(my_uuid, mongodb.Binary.SUBTYPE_UUID)},
                    function(err, result) { /* ... */ })

From the Mongo Shell , you get back that value as:

> db.test.find()
{ "_id" : ObjectId("557b2a390c59394b35236dc9"), "uuid" : BinData(4,"ke3D8CA2S/OUDNPWsKneAw==") }

Please note, the Mongo Shell UUID() function will produce a type 3 SUBTYPE_UUID_OLD binary:

> db.test.insert({uuid:UUID('09352d90756741879c25e108d83290a2')})
{ "_id" : ObjectId("557b2acc0c59394b35236dcb"), "uuid" : BinData(4,"ke3D8CA2S/OUDNPWsKneAw==") }
{ "_id" : ObjectId("557b2b7984ee2ba0375f4fc9"), "uuid" : BinData(3,"CTUtkHVnQYecJeEI2DKQog==") }
//                                                               ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM