我需要两个参数来搜索我的mongo集合,例如A和B.这个查询将保证返回3个集合中的一个,'历史',&#39 ;电流'或者'草稿'。
我想找到包含与参数A和B匹配的记录的集合,并使用promise在该记录上执行任务,无论在哪个集合中找到数据
这是代码的单数版本:
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语句中的情况下执行此操作?
答案 0 :(得分: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
}
希望这有帮助!