首先阅读我的代码
import { ObjectID } from 'mongodb';
import * as keygen from 'uid-generator';
// random friendly ObjectID generator
const MyObjectID = (id? : string) ObjectID => {
const uid = new keygen(null, keygen.BASE58, 12);
let objectId = id ? new Buffer(id, 'ascii') : new Buffer(uid.generateSync(), 'ascii');
return ObjectID(objectId.toString('hex')); // return MongoDB ObjectId
}
我基本上使用此库(uid-generator)
生成base58 12字节随机字符串然后将其转换为十六进制,然后使用带有MongoDB ObjectID的十六进制
看起来像这样
let oid = MyObjectID();
> ObjectId("7556685542544555317a7843") // string : 'uVhUBTEU1zxC'
db.mycollection.insert({ _id : oid, fieldX : "valueX" });
> { ok : 1 }
当我想查询数据时
oid = MyObjectID('uVhUBTEU1zxC')
db.mycollection.find({ _id : ObjectID(oid) });
> { _id : ObjectId("7556685542544555317a7843"), "fieldX" : "valueX" }
oid
ObjectId("7556685542544555317a7843")
oid.str
> '7556685542544555317a7843'
oid.getTimestamp()
> ISODate("2032-05-19T16:31:17Z") // it even gives a valid date, don't care about it much, it is not relevant for me to get the right exact timestamp from the ObjectID
这是正确的方法吗?这确保了系统的独特性吗?