【问题标题】:Construct Mongo ObjectId from timestamp with unique increment从具有唯一增量的时间戳构造 Mongo ObjectId
【发布时间】:2017-11-15 12:44:19
【问题描述】:

我想为要插入的文档生成 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 函数用于向 objectids 添加增量值。并且可以使用相同的时间戳生成 16777214 个不同的 objectid。任何有关如何使用此增量器来获得高达 16777214 的唯一时间戳的帮助表示赞赏。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    我尝试使用下面的 sn-p 生成随机 mongo objectid。

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

    它生成具有给定时间戳的随机 mongo objectid。

    【讨论】:

      猜你喜欢
      • 2016-12-02
      • 2016-02-19
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多