2017-09-04 107 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而不是回调函数。 –