比较mongoose _id和字符串

pat*_*pat 176 mongoose mongodb node.js

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

var results = new Object();

User.findOne(query, function(err, u) {
    results.userId = u._id;
}
Run Code Online (Sandbox Code Playgroud)

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

if (results.userId == AnotherMongoDocument._id) {
    console.log('This is never true');
}
Run Code Online (Sandbox Code Playgroud)

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

User id: 4fc67871349bb7bf6a000002 AnotherMongoDocument id: 4fc67871349bb7bf6a000002
Run Code Online (Sandbox Code Playgroud)

我假设这是某种数据类型问题,但我不知道如何将results.userId转换为数据类型,这将导致上述比较为真,我的外包大脑(又称谷歌)一直无法提供帮助.

cjo*_*ohn 319

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

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

等等.

  • `.equals()的文档`:http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#equals (9认同)
  • 如果你已经在使用`mongoose`,你可以只需要'('mongoose').mongo.ObjectID`,这样你就不必列出任何其他依赖项了 (3认同)
  • 我发现 doc._id == stringId 也可以工作,尽管由于严格的类型比较, doc._id === stringId 当然会是 false 。这更容易编码。 (2认同)

Joh*_*yHK 57

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

if (results.userId.equals(AnotherMongoDocument._id)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)


小智 20

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

  1. .equals像这样比较两个 mongoDocuments 上的 ObjectId 时使用
results.userId.equals(AnotherMongoDocument._id)
Run Code Online (Sandbox Code Playgroud)
  1. .toString()将 ObjectId 的字符串表示形式与 mongoDocument 的 ObjectId 进行比较时使用。像这样
results.userId === AnotherMongoDocument._id.toString()
Run Code Online (Sandbox Code Playgroud)

  • 第三种可能的解决方案是什么? (15认同)

Dil*_*ung 15

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


小智 9

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

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


r3w*_*3wt 8

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

以下是一个示例答案,以防您需要使用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);
});
Run Code Online (Sandbox Code Playgroud)

  • @Zlatko我不是新语法的忠实粉丝,而是他自己的每一个. (4认同)
  • @Zlatko`const exists = results.idList.some(val => val.toString()=== thisIsTheStringifiedIdWeAreLookingFor)`或`const exists = results.idList.some(val => val.equals(someModel._id))` (2认同)