2017-03-24 50 views
0

我有两个参数,我需要在A和B上搜索我的mongo集合。此查询将返回保证返回3个集合之一的结果'History' ,“当前”或“草稿”。查询几个MongoDb集合并执行相同的操作

我想找到一个包含该参数A和B一致的记录收集,并使用一个承诺,无论执行这个记录的一个任务

其收集的数据,发现这是一个奇异的版本的代码:

app.models.Current.find(_id: ObjectId('A'), version: 'B').exec(function(err, current) { 
    //Amend the record 
    ... 
}) 
.then(function() { 
    //Do stuff with the new record 
    ... 
}) 

有没有办法做到这一点,而不包括它在一个巨大的if语句?

回答

1

我不认为您可以在单个数据库调用中查询多个集合,但是您可以创建一个单一的承诺,在三个集合之一中找到文档后,这个承诺将会解决。它将类似于以下内容:

let promise = new Promise(
    function(resolve, reject){ 
    app.models.Current.find(_id: ObjectId('A'), version: 'B') 
     .exec(function(err,current) { 
      //Amend the record 
      ... 
      // If record exists and was amended, resolve with that record. 
      resolve(current); 
     }); 

    app.models.History.find(_id: ObjectId('A'), version: 'B') 
     .exec(function(err,history) { 
      //Amend the record 
      ... 
      // If record exists and was amended, resolve with that record. 
      resolve(history); 
     }); 
    ...(repeat for other collections)... 
    } 
).then(function(record){ 
    //Do something with the amended record 
} 

希望这有助于!