Reputation: 239
I have two parameters I need to search my mongo collections on, say A and B. This query will return be guaranteed to return a result from one of the 3 collections, 'History', 'Current' or 'Draft'.
I want to find the collection that contains a record that matches parameters A and B, and use a promise to perform a task on that record regardless of which collection the data was found in
This is the singular version of the code:
app.models.Current.find(_id: ObjectId('A'), version: 'B').exec(function(err, current) {
//Amend the record
...
})
.then(function() {
//Do stuff with the new record
...
})
Is there a way of doing this without wrapping it in a giant if statement?
Upvotes: 0
Views: 58
Reputation: 263
I don't believe that you can query multiple collections in a single database call, but you can create a single promise that will resolve after the document is found in one of the three collections. It will be similar to the following:
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
}
Hope this helps!
Upvotes: 1