node.js 比较猫鼬 _id 和字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11637353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:04:22  来源:igfitidea点击:

Comparing mongoose _id and strings

node.jsmongodbmongoose

提问by pat

I have a node.js application that pulls some data and sticks it into an object, like this:

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

var results = new Object();

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

When I do an if/then based on that stored ID, the comparison is never true:

当我根据存储的 ID 执行 if/then 时,比较永远不会为真:

if (results.userId == AnotherMongoDocument._id) {
    console.log('This is never true');
}

When I do a console.log of the two id's, they match exactly:

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

User id: 4fc67871349bb7bf6a000002 AnotherMongoDocument id: 4fc67871349bb7bf6a000002

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.

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

回答by cjohn

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.

Mongoose 使用 mongodb-native 驱动程序,它使用自定义 ObjectID 类型。您可以将 ObjectID 与.equals()方法进行比较。以你的例子,results.userId.equals(AnotherMongoDocument._id). ObjectID 类型还有一个toString()方法,如果您希望以 JSON 格式或 cookie 存储 ObjectID 的字符串化版本。

If you use ObjectID = require("mongodb").ObjectID(requires the mongodb-native library) you can check if results.userIdis a valid identifier with results.userId instanceof ObjectID.

如果您使用ObjectID = require("mongodb").ObjectID(需要 mongodb-native 库),您可以results.userId使用results.userId instanceof ObjectID.

Etc.

等等。

回答by JohnnyHK

ObjectIDs are objects so if you just compare them with ==you're comparing their references. If you want to compare their values you need to use the ObjectID.equalsmethod:

ObjectIDs 是对象,因此如果您只是将它们与==比较它们的引用进行比较。如果要比较它们的值,则需要使用以下ObjectID.equals方法:

if (results.userId.equals(AnotherMongoDocument._id)) {
    ...
}

回答by Dila Gurung

converting object id to string(using toString() method) will do the job.

将对象 id 转换为字符串(使用 toString() 方法)将完成这项工作。

回答by r3wt

The accepted answers really limit what you can do with your code. For example, you would not be able to search an array of Object Idsby using the equals method. Instead, it would make more sense to always cast to string and compare the keys.

接受的答案确实限制了您可以对代码执行的操作。例如,您将无法Object Ids使用 equals 方法搜索 的数组。相反,始终强制转换为字符串并比较键会更有意义。

Here's an example answer in case if you need to use indexOf()to check within an array of references for a specific id. assume queryis a query you are executing, assume someModelis a mongo model for the id you are looking for, and finally assume results.idListis the field you are looking for your object id in.

这是一个示例答案,以防您需要使用indexOf()来检查特定 id 的引用数组。假设query是您正在执行的查询,假设someModel是您正在寻找的 id 的 mongo 模型,最后假设results.idList是您正在寻找对象 ID 的字段。

query.exec(function(err,results){
   var array = results.idList.map(function(v){ return v.toString(); });
   var exists = array.indexOf(someModel._id.toString()) >= 0;
   console.log(exists);
});

回答by joy

According to the above,i found three ways to solve the problem.

根据以上内容,我找到了三种解决问题的方法。

  1. AnotherMongoDocument._id.toString()
  2. JSON.stringify(AnotherMongoDocument._id)
  3. results.userId.equals(AnotherMongoDocument._id)
  1. AnotherMongoDocument._id.toString()
  2. JSON.stringify(AnotherMongoDocument._id)
  3. results.userId.equals(AnotherMongoDocument._id)

回答by Father-Empire

The three possible solutions suggested here have different use cases.

这里建议的三种可能的解决方案具有不同的用例。

  1. Use .equals when comparing ObjectID on two mongoDocuments like this

    results.userId.equals(AnotherMongoDocument._id)

  2. Use .toString() when comparing a string representation of ObjectID to an ObjectID of a mongoDocument. like this

    results.userId === AnotherMongoDocument._id.toString()

  1. 在像这样比较两个 mongoDocuments 上的 ObjectID 时使用 .equals

    results.userId.equals(AnotherMongoDocument._id)

  2. 将 ObjectID 的字符串表示形式与 mongoDocument 的 ObjectID 进行比较时,请使用 .toString()。像这样

    results.userId === AnotherMongoDocument._id.toString()

回答by Jitendra

I faced exactly the same problem and i simply resolved the issue with the help of JSON.stringify()as follow:-

我遇到了完全相同的问题,我只是在以下帮助下解决了这个问题JSON.stringify():-

if (JSON.stringify(results.userId) === JSON.stringify(AnotherMongoDocument._id)) {
        console.log('This is never true');
}