2017-09-04 62 views
0

我有兩個收藏,比如carsowners。一個owner有很多cars。而one car只屬於one owner。當車主死亡時,我需要從cars集合中刪除所有車輛。爲了做到這一點,我在js中創建了腳本文件。 aliveOwnersundefined,這樣做的最好方法是什麼?是否有可能使用Mongoose如果在其他收藏中找不到物品,請從收藏中刪除物品

MongoClient.connect(url, (err, db) => { 
    assert.equal(null, err); 
    console.log('Connected successfully to server'); 
    var aliveOwners = db.collection('owner').find({}); // TODO. it should get only owner ids 
    console.log(aliveOwners); // undefined, mb cuz of non blocking 
    db.collection('cars').remove({ ownerId: { $nin: aliveOwners } })); //TODO. delete cars if owner id does not exist in aliveOwners 
}); 
+2

你爲什麼不簡單地把車內的細節嵌入車主的首位呢?這應該是你使用MongoDB的原因之一,如果你只是想把它當作一個RDBMS來處理,那就沒什麼意義了。你永遠不可能違反16MB的自有車。即使你是Jay Leno –

回答

0

找到方法是異步這就是爲什麼aliveOwners是不確定的。

你需要通過接收找到的文檔的回調函數,然後繼續你的代碼有:

db.collection('owner').find({}, function(err, aliveOwners) { 
    console.log(aliveOwners); 

    // Continue code 
}); 

注:由於汽車只屬於一個老闆,這可能是最好的,包括他們作爲所有者文件中的子文件。

+0

如果我有很多相關車型,車主 - >汽車 - >車輪,該怎麼辦?查找({},function(err,aliveOwners){console.log(aliveOwners); db.collection('cars')。find({},function(err, allCars){ //繼續代碼 //與車輪相同 }); });'。雖然它創建了很多嵌套的回調。處理這種情況的最佳方式是什麼? BTW什麼時候應該關閉數據庫連接? –

+0

您可以使用promise而不是回調函數。 –