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.
等等.
Joh*_*yHK 57
ObjectIDs是对象,所以如果你只是将它们与==你比较它们的引用进行比较.如果要比较它们的值,则需要使用以下ObjectID.equals方法:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
Run Code Online (Sandbox Code Playgroud)
小智 20
这里建议的三种可能的解决方案具有不同的用例。
.equals像这样比较两个 mongoDocuments 上的 ObjectId 时使用results.userId.equals(AnotherMongoDocument._id)
Run Code Online (Sandbox Code Playgroud)
.toString()将 ObjectId 的字符串表示形式与 mongoDocument 的 ObjectId 进行比较时使用。像这样results.userId === AnotherMongoDocument._id.toString()
Run Code Online (Sandbox Code Playgroud)
小智 9
根据以上内容,我找到了解决问题的三种方法。
AnotherMongoDocument._id.toString()JSON.stringify(AnotherMongoDocument._id)results.userId.equals(AnotherMongoDocument._id)接受的答案确实限制了您可以对代码执行的操作.例如,您将无法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)
| 归档时间: |
|
| 查看次数: |
81216 次 |
| 最近记录: |