我在 node.js 中使用 mongoose 查询 Oplog,使用以下代码获取最后一条 oplog 记录的时间戳:
oplogModel.find().sort('-ts').limit(1).select('ts').exec(function(err, res){
if (err) {console.log(err);}
lastTimestamp=res[0];
console.log(JSON.stringify(lastTimestamp));
});
但我得到的输出是 {"ts":"6260013777081597954"}
当我在 mongo shell 中运行它时,
rs0:PRIMARY> db.oplog.rs.find({}, {ts:1, _id:0}).sort({ts:-1}).limit(1);
我得到:{ "ts": Timestamp(1457523037, 2) }
如何将 {"ts":"6260013777081597954"}
转换为纪元时间或 iso 时间?
这个时间戳是什么格式的?
最佳答案
您得到的输出是因为 console.log(JSON.stringify(lastTimestamp))
行,因为 JSON.stringify(lastTimestamp)
将生成的对象解析为字符串。
本质上,您需要将时间戳转换为 32 位 int:
oplogModel.find().sort('-ts').limit(1).select('ts').exec(function(err, res){
if (err) {console.log(err);}
lastTimestamp=res[0].ts;
console.log(lastTimestamp); // 6260013777081597954
var h = 4294967296, // 2^32
timestamp = Math.floor(lastTimestamp / 4294967296), // convert to 32-bit int
date = new Date(timestamp * 1000); // Date() expects milliseconds.
console.log(date);
});
当你在 mongo shell 中得到 { "ts": Timestamp(1457523037, 2) }
时,第一个参数表示一个 32 位值,表示自 unix 纪元以来的秒数,第二个参数是 32 -bit ordinal value 用于对同一秒内发生的操作进行排序。
有关详细信息,请参阅 documentation但请记住,BSON 时间戳类型供 MongoDB 内部使用,在您自己的数据中,您应该更喜欢 Date 类型。
关于node.js - Mongoose 输出的未知时间戳格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35915591/