【问题标题】:Comparing two uuids in Node.js比较 Node.js 中的两个 uuid
【发布时间】:2015-06-30 08:48:23
【问题描述】:

我有一个问题,我在网上的研究中找不到任何答案。我在 Node.js 和 Cassandra 中开发一个 Web 应用程序。我目前正在开发一个通知系统,我必须比较两个 uuid 以确保我不会向做出原始操作(引发通知)的人发送通知。

问题是,当我比较两个应该相等的 uuid 时,我总是得到一个错误的值。

这是我目前正在处理的代码示例:

console.log('user_id :', user_id.user_id);
console.log("user id of the current user :", this.user_id);

console.log(user_id.user_id == this.user_id);
console.log(user_id.user_id === this.user_id);

这是结果的显示:

user_id : Uuid: 29f1227d-58dd-4ddb-b0fa-19b7fc02fbe8
user id of the current user : Uuid: 29f1227d-58dd-4ddb-b0fa-19b7fc02fbe8
false
false
user_id : Uuid: c8f9c196-2d63-4cf0-b388-f11bfb1a476b
user id of the current user : Uuid: 29f1227d-58dd-4ddb-b0fa-19b7fc02fbe8
false
false

如您所见,第一个 uuid 应该是相同的。它们是使用 nodejs cassandra 驱动程序中的 uuid 库生成的。 我不明白为什么当我能够在我的 Cassandra 数据库上使用指定的 uuid 发出任何请求时,我无法比较它们。

如果有人可以帮助我,我会很高兴!

【问题讨论】:

  • 什么是typeof user_id.user_idtypeof this.user_id?我打赌它们是(不同的)对象而不是字符串。原因是 id 在输出中以 Uuid: 为前缀,这可能来自对象的 toString() 实现。
  • 确实 user_id 和 this.user_id 都是不同的对象,这就是为什么简单的 === 不足以比较它们的原因。

标签: node.js cassandra comparison uuid


【解决方案1】:

正如 Ary 所说,内容相同但地址不同,因此比较返回 false。

cassandra-driver 的 UUID 对象提供了一个 equals 函数,用于比较 UUID 内容的原始十六进制字符串,您可以使用它:

> var uuid1 = uuid.fromString('29f1227d-58dd-4ddb-b0fa-19b7fc02fbe8')
> var uuid2 = uuid.fromString('29f1227d-58dd-4ddb-b0fa-19b7fc02fbe8')
> uuid1 == uuid2
false
> uuid1 === uuid2
false
> uuid1.equals(uuid2)
true

【讨论】:

  • 非常感谢,我不知道 cassandra-driver 的 UUID 对象中的 equals 方法。事实上,如果我将它们与这种方法进行比较,它会返回预期的结果。
【解决方案2】:

内容相同,但地址不应该。 如果您的比较返回 false,则可能是您的变量是 Object 类型。

【讨论】:

  • 确实如你所说,它们都是对象,所以我无法将它们与简单的 '===' 进行比较。
【解决方案3】:

我做了这样的事情,它的工作原理:

// assuming there are 2 uuids, uuidOne uuidTwo  
uuidOne.toString() === uuidTwo.toString()

【讨论】:

    【解决方案4】:

    看起来您的 user_id 实际上是一个“包含” Uuid 的对象,而不是 Uuid 本身。 user_id 对象不相同,但它们包含相同的数据。

    尝试直接比较 Uuid 的类似:

    console.log(user_id.user_id.Uuid == this.user_id.Uuid);
    console.log(user_id.user_id.Uuid === this.user_id.Uuid);
    

    【讨论】:

    • 'user_id'和'this.user_id'的显示是这样的,只是因为它们是对象。所以即使它显示'Uuid : value',它只是一个显示,Uuid不是对象的属性,所以'user_id.user_id.Uuid'和'this.user_id.Uuid'返回'undefined'。
    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多