B
B
bpGusar2019-10-11 16:42:13
MongoDB
bpGusar, 2019-10-11 16:42:13

How to execute multiple queries to mongodb and return only after all are completed?

I need to execute several queries .countDocumentsto the database, update the counter in each of them, and make returnthis counter.
I tried to do async / await, but for some reason it works every other time. One time the .thenupdated counter comes in, another time the standard 0 comes in.
Here's how I did it:

const countBookedAndOrderedBook = async () => {
            let bookedAndOrderedBooksArr = 0;

            await BookedBooks.countDocuments(
              { userId },
              (bookedBooksrr, countBookedBooks) => {
                if (bookedBooksrr) throw bookedBooksrr;
                console.log({ countBookedBooks });
                bookedAndOrderedBooksArr += countBookedBooks;
              }
            );

            return bookedAndOrderedBooksArr;
          };

          countBookedAndOrderedBook().then(count => {
            console.log(
              { count },
              servConf.maxBooksPerOneUserBookedAndOrderedAtTheSameTime
            );
...

If you make requests in a row, then some are executed when they want, apparently there is some kind of delay, and if you make several requests in a row and then display console.log(count)it, the count will be 0, and if you output it to the console by timeout, then everything is fine, but the timeout is nonsense.
In the example, there is one request, but in theory there should be many.
Maybe I'm doing it wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bpGusar, 2019-10-11
@bpGusar

Made with async

parallel(
            [
              function(callback) {
                BookedBooks.countDocuments({ userId }, callback);
              }
            ],
            function(asyncErr, results) {
              if (
                results[0] <=
                servConf.maxBooksPerOneUserBookedAndOrderedAtTheSameTime - 1
              )
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question