我知道可以通过数据库调用找到它,但出于好奇,例如在 Node 中,如果我有一个 Mongoose 文档 ID 数组。我如何针对该数组模拟 indexOf 函数以确定其中是否有另一个 mongoId?
我只是问一下,因为直接比较 id 是行不通的,需要使用 `objectId.equals()' 函数。是否有 mongoose/mongoId 函数可以为 ID 执行类似于 indexOf 的操作?
最佳答案
如果您的问题是您不确定比较中哪个是字符串或哪个是 ObjectId,那么只需将所有内容转换为“字符串”。所有对象都有.toString()
,甚至是字符串。对于数组转换,只需使用 .map()
。
例子:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var objSchema = new Schema({
});
var Obj = mongoose.model('Obj',objSchema);
var arrayTest1 = [],
arrayTest2 = [];
for ( x = 0; x < 10; x++ ) {
var obj = new Obj();
arrayTest1.push( obj.id );
arrayTest2.push( obj.id.toString() );
}
var el1 = arrayTest1[4],
el2 = arrayTest2[3];
[el1,el2].forEach(function(el) {
console.log( el );
});
console.log( arrayTest1.indexOf(el1) );
console.log( arrayTest2.indexOf(el2) );
console.log( arrayTest1.map(function(el) {
return el.toString()
}).indexOf(el1.toString()));
console.log( arrayTest2.map(function(el) {
return el.toString()
}).indexOf(el2.toString()));
两对语句都评估为正确的索引匹配。所以第二种形式对对象类型是通用的。 ObjectId 或 sting 在任一侧。
关于node.js - 如何在数据库调用之外的 mongoIds 数组中找到 mongoId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28061589/