如何将函数logic
传递给find
函数以便在每个文档上使用它?
我试图用属性中的某些值递归地查找Mongo文档。我已经定义了一个“算法”,并希望这个find
- 函数,但尽管阅读了查询,搜索和find()
,我没有运气。
// match every node with propertyname "Reference" with the exact value "43_1"
var logic = function(currentKey, currentValue) {
return ( currentKey == "Reference" && currentValue === "43_1" );
};
db.getCollection('metavalg').find(function() {
function recurSearchObj(doc) {
return Object.keys(doc).some(function(key) {
if ( typeof(doc[key]) == "object" && doc[key] !== null ) {
return recurSearchObj(doc[key]);
} else {
// invoke matching-logic
return logic(key, doc[key]);
}
});
}
// search document recursively
return recurSearchObj(this);
})
在弗拉基米尔M的帮助下,我最终重新编写代码并执行此操作:
db.getCollection('metavalg').find(function() {
function inspectObj(doc, logic) {
return Object.keys(doc).some(function(key) {
if ( typeof(doc[key]) == "object" && doc[key] !== null ) {
return inspectObj(doc[key], logic);
} else {
return logic(key, doc[key]);
}
});
}
return inspectObj(this, function(currentKey, currentValue) {
return ( currentKey == "Nummer" && currentValue === "43_1" );
//return ( currentKey == "Navn" && /max\.? 36/i.test(currentValue) );
});
})
答案 0 :(得分:0)
您可以将逻辑方法作为参数传递给recurcive搜索对象:
// match every node with propertyname "Reference" with the exact value "43_1"
var logic = function(currentKey, currentValue) {
return ( currentKey == "Reference" && currentValue === "43_1" );
};
db.getCollection('metavalg').find(function() {
function recurSearchObj(doc, aLogic) {
return Object.keys(doc).some(function(key) {
if ( typeof(doc[key]) == "object" && doc[key] !== null ) {
return recurSearchObj(doc[key], aLogic);
} else {
// invoke matching-logic
if( aLogic(key, doc[key]) ){
// then do somthing
}
}
});
}
// search document recursively
return recurSearchObj(this, logic);
});