【发布时间】: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 的唯一时间戳的帮助表示赞赏。
【问题讨论】: