首页 > 解决方案 > 给定两个 mongodb Id 如何确定哪个更旧

问题描述

假设我们有:

const a = ObjectId()
const b = ObjectId() 

我们能不能做 if(a > b) {...}

如果它们是字符串呢?

  const a = String(ObjectId())
  const b = String(ObjectId())

我们应该使用 localComapre 还是 > 仍然足以比较哪个更老/更年轻?

标签: node.jsmongodb

解决方案


ObjectId对象包含时间戳,您可能想要比较它们。

const a = new ObjectId()
const b = new ObjectId()

if(a.getTimestamp() > b.getTimestamp()) {...}

字符串相同:

const a = String(new ObjectId())
const b = String(new ObjectId())

if((new ObjectId(a)).getTimestamp() > (new ObjectId(b)).getTimestamp()) {...}

推荐阅读