Mongoose 输出的时间戳格式未知。

4

我正在使用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"}转换为epoch时间或iso时间? 这个时间戳是什么格式?


这里应该查看文档 - chridam
这里出了些问题。使用bson-timestamp库将Mongo中获取的时间戳转换为整数会得到完全不同的结果。 - elssar
1个回答

1
你得到的输出是因为这一行代码 console.log(JSON.stringify(lastTimestamp)),因为JSON.stringify(lastTimestamp)将结果对象解析为字符串。
本质上,你需要将时间戳转换为32位整数:
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) }时,第一个参数表示自unix纪元以来的秒数,是一个32位值,第二个参数是32位序数值,用于对在同一秒发生的操作进行排序。
更多细节,请参考文档,但请记住,BSON时间戳类型是为MongoDB内部使用而设计的,在您自己的数据中,应优先选择Date类型。

我正在查询oplog,这是一个内部只读集合,因此我无法选择它的日期时间。 - Shipra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接