[英]NodeJs: Filter mongo query results with results from another collection
我遇到一種情況,需要對mongo集合(A)的一組不同值執行邏輯,然后將結果保存到另一個集合(B)。 但是(A)的內容會隨着時間而變化,因此我只想對(B)中沒有相應文檔的(A)中的那些文檔執行邏輯。 由於不支持聯接,因此我嘗試在節點級別執行此操作。 我正在查詢集合(A)中的所有項目,並使用findOne
在集合(B)中查找相應的條目。 如果找到它,我想將其從數組中刪除,但是我被卡住了,因為findOne
使用了異步回調,該回調似乎不適用於數組filter
方法。 有一個更好的方法嗎:
function loadNewDocumentsFromDB(callback){
db.collection('A', function(err, acollection){
bcollection.find().toArray(function(err, arr){
if(arr){
// toQuery is the global array to be used elsewhere
toQuery = arr.map(function(config){
transformed =
{
args: config._id, // these args are a doc representing a unique entry in 'B'
listings: config.value.id.split(',') // used by other functions
};
return transformed;
})
.filter(function(transformed){
db.collection('B', function(err, bcollection){
bcollection.findOne(transformed.args, function(err, doc){
// I want these values returned from the filter function not the callback
if(doc){
return false; // want to remove this from list of toQuery
}else{
return true; // want to keep in my list
});
});
}
callback();
});
});
}
這就是我設法使其工作的方式:
function loadOptionsFromDB(callback){
toQuery = [];
db.collection('list', function(err, list){
db.collection('data', function(err, data){
list.find().each(function(err, doc){
if(doc){
transformed =
{
args: doc._id,
listings: doc.value.id.split(',')
};
(function(obj){
data.findOne(obj.args, function(err, found){
if(found){}
else{
toQuery.push(obj);
}
});
})(transformed);
}else{
//Done finding
setTimeout(callback, 20000);
}
});
});
});
}
更好的方法是在數據庫上執行此操作。 檢查是否有兩次執行http://docs.mongodb.org/manual/core/map-reduce/對您有用。 有關更多信息,請參見在MongoDB中合並兩個集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.