从具有唯一增量的时间戳构造 Mongo ObjectId



我想为要作为新文档插入的文档生成 mongo objectid,并覆盖时间戳值。 所以我使用下面的代码来获取 objectid。

var oIdWithTimestamp = function (timestamp) {
    // Convert string date to Date object (otherwise assume timestamp is a date)
    if (typeof (timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }
    // Convert date object to hex seconds since Unix epoch
    var hexSeconds = Math.floor(timestamp / 1000).toString(16);
    // Create an ObjectId with that hex timestamp
    var constructedObjectId = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");
    return constructedObjectId
};

但是,如果我想插入 2 个具有相同时间戳的文档,它并不能满足需求。我注意到有一个get_inc函数用于向对象标识符添加增量值。并且16777214可以使用相同的时间戳生成不同的对象ID。 有关如何使用此增量器获取最多16777214的唯一时间戳的任何帮助,我们将不胜感激。

我尝试使用以下代码片段生成随机 mongo objectid。

var bson = require('bson');
var generateObjIdFromTime = function(spefictime) {
    spefictime = ~~(spefictime/1000);
    return bson.ObjectID(spefictime);
}  

它生成具有给定时间戳的随机 mongo 对象 id。

最新更新