问题描述
我有一个 node.js 应用程序,它提取一些数据并将其粘贴到一个对象中,如下所示:
I have a node.js application that pulls some data and sticks it into an object, like this:
var results = new Object();
User.findOne(query, function(err, u) {
results.userId = u._id;
}
当我根据存储的 ID 执行 if/then 时,比较永远不会为真:
When I do an if/then based on that stored ID, the comparison is never true:
if (results.userId == AnotherMongoDocument._id) {
console.log('This is never true');
}
当我执行两个 ID 的 console.log 时,它们完全匹配:
When I do a console.log of the two id's, they match exactly:
User id: 4fc67871349bb7bf6a000002 AnotherMongoDocument id: 4fc67871349bb7bf6a000002
我假设这是某种数据类型问题,但我不确定如何将 results.userId 转换为将导致上述比较为真的数据类型,而我的外包大脑(又名 Google)无法帮助.
I am assuming this is some kind of datatype problem, but I'm not sure how to convert results.userId to a datatype that will result in the above comparison being true and my outsourced brain (aka Google) has been unable to help.
推荐答案
Mongoose 使用 mongodb-native 驱动程序,它使用自定义 ObjectID 类型.您可以使用 .equals()
方法比较 ObjectID.以您的示例,results.userId.equals(AnotherMongoDocument._id)
.ObjectID 类型还有一个 toString()
方法,如果您希望以 JSON 格式或 cookie 存储 ObjectID 的字符串化版本.
Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the .equals()
method. With your example, results.userId.equals(AnotherMongoDocument._id)
. The ObjectID type also has a toString()
method, if you wish to store a stringified version of the ObjectID in JSON format, or a cookie.
如果你使用 ObjectID = require("mongodb").ObjectID
(需要 mongodb-native 库)你可以检查 results.userId
是否是一个有效的标识符results.userId instanceof ObjectID
.
If you use ObjectID = require("mongodb").ObjectID
(requires the mongodb-native library) you can check if results.userId
is a valid identifier with results.userId instanceof ObjectID
.
等
这篇关于比较猫鼬 _id 和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!