Attempting to grasp the concept of implementing Promise in JavaScript

Currently, I am utilizing the native driver for mongoDB in my project. Within the database, there are approximately 7 collections that I need to work with. My goal is to create a variable that holds the count of entries in each collection except for the last one. Then, I want to create another variable specifically for the entries in the last collection. Finally, I intend to pass these variables through the res.render() command to display them on the webpage.

The main issue I'm facing here is that I am accustomed to synchronous execution of functions, which unfortunately does not apply in this scenario.

Below is the code snippet representing how I would approach this if everything were executed synchronously:

var count = 0;
db.listCollections().toArray(function(err,collection){
   for(i = 1; i < collection.length;i++){
      db.collection(collection[i].name).count(function(err,value){
         count = count + value;
      })
   }
   var count2 = db.collection(collection[i].name).count(function(err,value){
         return value;
      })
   res.render('index.html',{data1: count, data2: count2})
})

Clearly, the above code does not achieve what I intended. I attempted to work with promises to solve the issue but only ended up more confused.

Answer №1

To achieve this outcome using Promises, consider the following approach:

Retrieve collection names, loop through them while returning either the count or entries (if it's the last collection). Finally, calculate and send the total counts to the client.

db.listCollections().toArray()
    .then(collections => {
        let len = collections.length - 1
        return Promise.all(collections.map(({name}, i) => {
          let curr = db.collection(name)
          return i < len ? curr.count() : curr.find().toArray()
        }
        ))
      }
    )
    .then(res => {
      let last = res.pop(),
          count = res.reduce((previous, current) => previous + current)
      res.render('index.html', {count, last})
    })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with uploading multiple files in Yii2

I recently attempted to implement a solution from this link, but unfortunately, it's not functioning as expected on my end. Despite no error messages, the data isn't being saved in the MongoDB database. Below are snippets of the code I am using: ...

Is there a restriction on the maximum size of a MongoDB database

We're looking into implementing MongoDB for our database needs but are curious if it offers the capability to restrict database or table sizes. For instance: db.user1.find() db.user2.find() In the scenario above, each user will have their own datab ...

Remove the "href" from Zend2 navigation functionality

When using Zend2 navigation from an array passed in Zend\Navigation\Navigation, everything works smoothly if child items are opened on parent item mouse hover. However, undesirable actions occur when they are opened on mouse click, as the user is ...

Dealing with undefined properties in Javascript can cause errors

[ { dateTime: '2016-03-30 05:55:53', value: '4.0' }, { dateTime: '2016-03-30 05:55:55', value: '17.0' }, { dateTime: '2016-03-30 05:55:57', value: '17.0' }, { dateTime: '2016-03-30 06:0 ...

What is the best way to add elements using JavaScript when a particular character is present?

Current: <p id="article">忙著端出 高階 DSLR 產品的 Nikon ,總算想到了在 兩年半之後 更新自己的入門系列數位單眼相機,端出 Nikon D3400。很好的產品</p> I want to divide the text whenever certain charac ...

delaying the alteration of an image attribute following an AJAX call

After clicking on a button, a function is triggered (think of it as a published/unpublished button). Immediately after the function is activated, I change the element to display a loader gif. function updateStatus(event, status, element, data, action) { ...

Generate a JSON document to download and be stored in browser's memory as a JSON file

Is there a way to generate a JSON (or XML) page in PHP that allows users to save the file with the correct extension in their browser? <?php header('Content-type: application/json'); echo (file_get_contents('some.json', true ...

What is the best way to access the iframe element?

This is main.html <body> <iframe id="frame" src="frame.html"></iframe> <script type="text/javascript"> document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = &apos ...

Troubleshooting Node.js TypeScript breakpoints in Visual Studio Code

I've attempted multiple solutions, but none seem to be working for me. Although the code is running, I'm having trouble setting breakpoints and debugging it. Can you offer any assistance? Below is the configuration script I've tried in VSCo ...

Apply the animate.css classes before removing the element

I'm struggling to add and remove CSS classes on my label/checkbox tick, as well as removing the item once it's been checked. I can only manage to do one of these tasks at a time. $(function () { $("label[for='<%= @todo.id %>' ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

Troubleshooting the issue with the htmlFor attribute

I have encountered an issue with creating radio buttons and labels using JavaScript. Despite adding the 'for' attribute in the label using 'htmlFor', it does not apply to the actual DOM Element. This results in the label not selecting t ...

Accepting PUT requests on a JavaScript web server

I'm facing an issue retrieving PUT requests from a service within my Angular application. The problem lies in the fact that I cannot access the data from the request's body as it returns undefined. Below is the code snippet for reference. ANGULA ...

Express fails to handle the POST request

Using ejs, express, nodeJS and mySQL has been great so far. However, I'm facing an error with this code: Cannot POST /search. I believe the index.ejs and app.js files are okay, but I suspect there's a problem with the searchRouter... app.js cons ...

At what point is the resolution of two-way binding for services injected into a controller typically completed?

I am puzzled by the behavior of the code snippet below, as it only produces the following output: Array [] Array [object, object] Instead, when submitting the form, I anticipate the output to be: Array [object, object] Array [object, object] You can vi ...

Pair up balls that have matching numbers

A software application was designed with the following features: It can create 4 balls on the screen, each containing a numerical value Users have the ability to input values for new circles to be generated Upon clicking a button, 4 new circles with num ...

What could be causing the lack of data with 'react-hook-form'?

I have encountered an issue while working with react-native and using 'react-hook-forms' for creating dynamic forms. The problem is that the data object returned is empty, even though it should contain the values entered in the input fields. When ...

Enhancing the performance of your code by optimizing it using jQuery when a checkbox is either checked or

Looking for ways to optimize a jquery function that toggles a URL parameter based on checkbox status. Any suggestions on how to streamline this code? $('#mapControl').live('click', function(){ var thisUrl = $(location).attr(' ...

What is the process of querying and organizing data in mongoDb?

Section A: In my collection of students: { sname : "", studentId: "123" age: "", gpa: "", } I want to extract only two keys: { sname : "", studentId: "123" } To achieve this, I need to remove age and gpa fields and retain onl ...

What is the best way to use jQuery to select a group of table rows based on the value of a

My current issue involves using a jQuery selector to move table rows "UP" and "Down." Here is the Table structure in HTML: jQuery Portion : $(".up,.down").click(function() { var row = $(this).parents("tr:first"); if ($(this).is(".up")) { ...