比较猫鼬_id和字符串 [英] Comparing mongoose _id and strings
问题描述
我有一个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
我假设这是某种数据类型问题,但是我不确定如何将result.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类型.您可以将ObjectID与.equals()
方法进行比较.在您的示例中,results.userId.equals(AnotherMongoDocument._id)
.如果您希望以JSON格式或Cookie来存储ObjectID的字符串化版本,则ObjectID类型也具有toString()
方法.
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本地库),则可以使用results.userId instanceof ObjectID
检查results.userId
是否是有效的标识符.
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和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!