0

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?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.