object.valueOf(),如果返回false

object.valueOf() if returns false

本文关键字:如果 返回 false valueOf object      更新时间:2023-09-26

我对JavaScript中的类如何工作感到困惑,我一直知道它稍微复杂一些,但现在我完全不知道。下面的代码和输出。

以下json存储在mongodb中。我怀疑这可能是错误的地方。

console.log(JSON.stringfy(用户)):

{"_id":"5687f787f8ad41175fab5bd5","pic":"karl.png","language":"5687f787f8ad41175fab5bd2","cell":1,"local":{"email":"karl.morrison@email.com","password":"12345"},"profile":{"name":"Karl Morrison"},"sessions":[{"id":"5687f79bf8ad41175fab5bd9","seen":false,"active":false}]}

console.log(JSON.stringfy(消息)):

{"authorId":"5687f787f8ad41175fab5bd5","upvotes":0,"created":"2016-01-02T16:15:23.621Z","message":"<p>aa</p>"}

Ze代码:

console.log('"' + user._id.valueOf() + '" "' + message.authorId.valueOf() + '"');
console.log({}.toString.call(user._id).split(' ')[1].slice(0, -1).toLowerCase());
console.log({}.toString.call(message.authorId).split(' ')[1].slice(0, -1).toLowerCase());
if (user._id.valueOf() == message.authorId.valueOf()) {
    console.log('TRUE');
} else {
    console.log('FALSE');
}

控制台:

"5687f787f8ad41175fab5bd5" "5687f787f8ad41175fab5bd5"
object
object
FALSE

我不明白为什么不返回TRUE?

根据mongodb文档:

在版本2.2中更改:在以前的版本中ObjectId.valueOf()返回ObjectId()对象。

由于user._idmessage.authorIdObjectId对象,因此常规的==比较它们的引用,从而得到false

尝试使用其中一种:

  • user._id.toString() == message.authorId.toString()
  • user._id.equals(message.authorId)
  • 升级到更新的mongodb驱动程序