How can promises be used in place of executing multiple mongoose queries?

Looking for a solution to avoid nested callbacks in the following code:

app.get '/performers', (req, res) ->
    conductor = require('models/conductor').init().model
    soloist = require('models/soloist').init().model
    orchestra = require('models/orchestra').init().model
    chamber = require('models/chamber').init().model
    performers = {}
    conductor.find {}, (err, result) ->
        performers.conductor = result
        soloist.find {}, (err, result) ->
            performers.soloist = result
            orchestra.find {}, (err, result) ->
                performers.orchestra = result
                chamber.find {}, (err, result) ->
                    performers.chamber = result
                    res.json performers

Any suggestions on how to refactor this?

Answer №1

When it comes to handling asynchronous operations, I personally prefer using the async library over promises. Specifically, in situations like this, leveraging async.parallel can be quite effective.

Although not an expert in coffeescript, the code snippet below demonstrates how it could potentially be implemented:

performers = {}
async.parallel [
    (callback) ->
        conductor.find {}, (err, result) ->
            performers.conductor = result
            callback err
    (callback) ->
        soloist.find {}, (err, result) ->
            performers.soloist = result
            callback err
    (callback) ->
        orchestra.find {}, (err, result) ->
            performers.orchestra = result
            callback err
    (callback) ->
        chamber.find {}, (err, result) ->
            performers.chamber = result
            callback err
    ], (err) ->
        res.json performers

Answer №2

One way to structure your code is by following this pattern:

exports.display = function(req, res){
    var _self = {};

    var retrieveProducts = function(err, products){
      _self.products = products;
      res.render('display', { user: _self.user, products: _self.products, categories: _self.categories });
    };

    var retrieveCategories = function(err, categories){
      _self.categories = categories;
      Products.find().exec(retrieveProducts);
    };

    var retrieveUser = function(err, user){
      _self.user = user;
      Categories.find().exec(retrieveCategories);
    };

    User.findById(user).exec(retrieveUser);
};

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

Error encountered when trying to submit registration form, POST request failed

I am currently working on developing a web application that includes a login and registration form. However, I have been facing an issue where the registration fails every time I attempt to register a new user. Below is the code snippet for the POST method ...

Unable to establish an external connection with the node

Currently, I am in the process of establishing a connection to a local server and running an app on port 8080 using node. Both node and apache are installed on my system. When Apache is active, I can access the server externally. However, when Node is runn ...

Trouble arises when attempting to showcase document fields in MongoDB

As a beginner in programming, I am putting in my best effort to figure things out on my own. However, I seem to be stuck without any guidance. I am attempting to display all products from the mongoDB based on their brand. While I have successfully set up a ...

Ways to obtain parameter from URL in Express without diving into the request object

const express = require('express'); const app = express(); app.use('/', anyroute); // in anyroute file router.route('/:id').get(controlFunction) controlFunction(req, res, res)=> { // Here we can get the "id" fr ...

Node: encountering network issues - unable to resolve res.status(404) operation

class gameInfo { static async gameeee(req, res) { try { console.log(req.body); await db.adb .collection("game") .findOne({ req.body.gameID}, async (err, result) => { console.log("a"); ...

How can rate limiting be integrated into an express.js application?

How can rate limits per IP be effectively implemented in a Node.js Express API App? const express = require('express') const app = express() const port = 3000 // where should the rate limiting logic go? app.post('/test', (req, res) =&g ...

The mysterious nature of view binding in Ember.js

Here's a unique challenge I'm facing. I've developed a sidebar component called SortableStopView that extends CollectionView. This sidebar contains a scrollable and sortable list of 'stops' which users can click on to navigate to t ...

Using a FOR LOOP in Node.js where each iteration requires the result of the previous one

I am trying to create a loop in Node JS that requires the result of the previous iteration. function jsonParser(txt_file, cb) { var perc = 0; lines = txt_file.split('\n'); insert_communication = 'INSERT INTO communication (account_i ...

Is it possible to run a React, Vite, Node.js, and Express app all at once

I am currently learning React and JavaScript, but I am facing challenges when it comes to connecting my frontend and backend. I have been attempting to run both the front and back end simultaneously in order to send requests to the backend and display fetc ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

The only information returned from calling mongoose's Model.save() method are the fields { _id, __

I've encountered a problem even though I believe I'm following all the right steps. I'm attempting to save an item from a form into my mongodb collection using mongoose. This is what my schema looks like: // stationmodel.js export const Sta ...

Refresh the screen after 10 seconds

Apologies if I'm not explaining this well in advance. I am looking to create a dynamic webpage using JavaScript that automatically updates every 10 seconds. Does anyone have an example code snippet for this? **Specifically, allow ...

What could be the reason for the onmessage listener not handling the initial SSE event?

When a client connects to a Node Express server, it creates a new EventSource. The server sends an SSE event upon initial connection and then at a 30-second interval thereafter. Strangely, the client's onmessage handler does not respond to the initial ...

What is the functionality of an Angular service that retrieves an

It appears that Angularjs services are constructed by passing in a Contructor function: app.service('serviceName', function(){ this.var1 = 'foo'; this.method1 = function(){ } }); Angular executes this function using the new ...

What is the most effective method for grouping state updates from asynchronous calls in React for efficiency?

After reading this informative post, I learned that React does not automatically batch state updates when dealing with non-react events like setTimeout and Promise calls. Unlike react-based events such as onClick events, which are batched by react to reduc ...

Dealing with null values from JSON when a list view row is clicked: Tips and suggestions

My knowledge of Java is limited, but I managed to pull data from an API to a list view successfully. However, when trying to display more details upon clicking on an item in the list view, I encountered errors related to handling null results in my text vi ...

Tips for effectively structuring express routes

Struggling to understand how to effectively utilize the /:variable notation. My current setup includes this layout: router.route("/").get() router.route("/:id").get().put().post().delete() router.route("/auth").get().put().pos ...

Setting up reverse proxy rules for GitLab on a Node.js Express server can be achieved using the following

I am currently in the process of developing a Node.js application to serve a private GitLab server. Initially, I had it set up with Apache, but now I am looking to switch over to using my Node.js application instead. Most of the functionality is there. Th ...

Contrasting location versus redirect features in Node.js

Can someone explain the difference between res.location() and res.redirect() methods? I know that res.redirect() is used to redirect to a specific URL, but I'm not sure about the purpose of res.location(). When I tried using res.location() before res. ...

Issue with Node.js: req.session data does not persist

Currently, I am working on integrating a login feature using express, nuxtjs, and express-session. The functionality works well without any issues until the page is refreshed. However, after refreshing the page, the session data is not retained. I have co ...