我有一个node.js应用程序,它可以提取一些数据并将其粘贴到对象中,如下所示:

var results = new Object();

User.findOne(query, function(err, u) {
    results.userId = u._id;
}

当我基于存储的ID执行if / then时,比较永远不会成立:
if (results.userId == AnotherMongoDocument._id) {
    console.log('This is never true');
}

当我执行两个ID的console.log时,它们完全匹配:
User id: 4fc67871349bb7bf6a000002 AnotherMongoDocument id: 4fc67871349bb7bf6a000002

我以为这是某种数据类型问题,但是我不确定如何将result.userId转换为数据类型,从而导致上述比较正确,而我的外包大脑(又名Google)无法提供帮助。

最佳答案

Mongoose使用mongodb本机驱动程序,该驱动程序使用自定义ObjectID类型。您可以将ObjectID与.equals()方法进行比较。在您的示例中,results.userId.equals(AnotherMongoDocument._id)。如果您希望以JSON格式或Cookie来存储ObjectID的字符串化版本,则ObjectID类型也具有toString()方法。

如果您使用ObjectID = require("mongodb").ObjectID(需要mongodb本机库),则可以使用results.userId检查results.userId instanceof ObjectID是否为有效标识符。

等等。

07-28 02:42
查看更多