Implement a mandatory route in Express

Is it possible to enforce a specific route?

Scenario:

Consider the following route A:

notiSchema = notification model

router.get('/set', function(req, res){
    User.findById("userId", function(err, foundUser){
        foundUser.notiSchemaSent.forEach(function(notiSchema, i){
            if(req.user.notifications.length === 0){
                req.user.notifications.unshift(notiSchema);
                req.user.save();
            } else {
                req.user.notifications.forEach(function(userSchema, i){
                    if(req.user.notifications.indexOf(notiSchema) === -1){
                         req.user.notifications.unshift(notiSchema);
                         req.user.save();
                    }
                });
            }
        });
    });

    res.json(req.user.notifications);
});

The issue here is that the 'res.json' line is executed before userB is updated

Therefore, I have created another route B:

router.get('/get', middleware.isLoggedIn, function(req, res){
  res.json(req.user.notifications);
});

Here is my Ajax request:

$.get('/set', function(data){
    // Adding "fa-spin" class here only
}).then(function(){
    $.get('/get', function(data){
        $(data).each(function(i, item){
            $('.notDrop').prepend(item);
        });

        // Remove the "fa-spin" class
    });
}); 

However, there are instances where route "B" is called before route "A" is fully completed;

Thus, I am curious to know if it's feasible to trigger route "B" only after route "A" has completely finished processing.

Answer №1

I have revised the route to consolidate all changes into req.user.notifications, saving only once at the end if the array was modified. This approach allows for a single .save() operation with a callback function to indicate when it's completed.

Key modifications:

  1. Accumulate changes in the array and save at the end.
  2. Save only if the array was altered.
  3. Removed special case for .length === 0 as it's unnecessary.
  4. Implemented a callback on req.user.save() for tracking completion and sending response post-save.
  5. Incorporated error handling for both .save() and .findById().

Here is the updated code snippet:

router.get('/set', function(req, res){
    User.findById("userId", function(err, foundUser){
        // Error handling for finding user
        if (err) {
           console.log(err);
           res.status(500).send("Error finding user.")
           return;
        }
        let origLength = req.user.notifications.length;
        foundUser.notiSchemaSent.forEach(function(notiSchema, i){
            req.user.notifications.forEach(function(userSchema, i){
                if(req.user.notifications.indexOf(notiSchema) === -1){
                    req.user.notifications.unshift(notiSchema);
                }
            });
        });
        // Save only if there are modifications in notifications array
        if (req.user.notifications.length !== origLength) {
            req.user.save(function(err) {
                // Error handling for saving user notifications
                if (err) {
                    console.log(err);
                    res.status(500).send("Error saving user notifications.")
                } else {
                    res.json(req.user.notifications);
                }
            });
        } else {
            res.json(req.user.notifications);
        }
    });
});

If you adjust your database code to retrieve an array of users from the find operation, you can process them as follows:

router.get('/set', function(req, res){
    User.find({_id: {$in: arrayOfIds}}, function(err, foundUsers){
        // Error handling for finding multiple users
        if (err) {
           console.log(err);
           res.status(500).send("Error finding user.")
           return;
        }
        let origLength = req.user.notifications.length;
        foundUsers.forEach(function(foundUser) {
            foundUser.notiSchemaSent.forEach(function(notiSchema, i){
                req.user.notifications.forEach(function(userSchema, i){
                    if(req.user.notifications.indexOf(notiSchema) === -1){
                        req.user.notifications.unshift(notiSchema);
                    }
                });
            });
        });
        // Save only if there are modifications in notifications array
        if (req.user.notifications.length !== origLength) {
            req.user.save(function(err) {
                // Error handling for saving user notifications
                if (err) {
                    console.log(err);
                    res.status(500).send("Error saving user notifications.")
                } else {
                    res.json(req.user.notifications);
                }
            });
        } else {
            res.json(req.user.notifications);
        }
    });
});

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

"Unraveling nested data structures in React using JSON parsing

When attempting to fetch data in React from a MySQL database, I have encountered an issue where MySQL auto-escapes my values, including nested objects. While I am able to use the .json() function successfully on the top-level, I have run into problems when ...

You should be providing a string value as expected. It seems that you may have overlooked exporting your component from the correct file it was defined in, or perhaps there is confusion with default and named

I encountered a strange error despite meticulously organizing and exporting/importing files. The code is structured from components to the App render method. Item.js import React from 'react'; import './Global.css' const Item = ({data ...

Utilizing MVC3 to make an Ajax call in Jquery to store data in a database

I am currently developing an MVC3 application. The script code on my view page looks like this- <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script> <script type="text/javascript"> $(function () { ...

The discriminator value 'SqlException' is unrecognized. Is there a way to bypass the discriminator on a dynamic type?

I am working with a model similar to the one shown below: [BsonIgnoreExtraElements] public class MongoDbLogModel { public string Level { get; set; } public string RenderedMessage { get; set; } [BsonDateTimeOptions(Kind = DateTimeKind.Local)] ...

Passing an Integer as a string in Swift to Express using Query Strings

I'm currently facing an issue with passing a query string from Swift to Express. I am sending [String: Any] data in the following manner: let params = ["id": 1] The function I'm sending it to is performing the following actions: postSt ...

The radio button functionality is not functioning properly as intended

Having trouble with the current code that utilizes HTML and JavaScript. There is an HTML table on the page with a radio button and 4 other fields. The table is generated dynamically when values are set through the controller. It is also possible to add new ...

When using Reactjs with leaflet-routing-machine, the waypoint is rendered twice

While attempting to use the leaflet-routing-machine library, I encountered a bug. The issue is that the "Waypoints" section is rendering twice. Why is this happening? Can anyone offer assistance? Thank you https://i.sstatic.net/MlkQ2.jpg My code is lis ...

Java Spring error encountered when attempting to create a bean with the annotations @Service, @Controller, or @

Can someone please assist me? I have been struggling with this error for the past 2 days. I am encountering the following error: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adsController': Unsa ...

Verify if the JSON attribute is empty

My input contains the following: { "headers": { ... }, "body": { "RequestInfo": { ... , "Identificator": null } } <filter regex="false" source="boolean($ctx:Identificator)"> - check if it exists (even when it's ...

Ajax is failing to receive the PHP response

I've been struggling with retrieving values from the database using AJAX during the window load event. When I directly access the PHP script, I see the correct values on the screen. However, when trying to fetch these values through AJAX on another pa ...

Why does Javascript Tic-Tac-Toe delay notifying the user until the entire board is full?

There have been a lot of questions about Tic-Tac-Toe javascript, but my issue is unique. My code works fine, but it doesn't declare a winner or a tie game until the entire board is filled. I suspect that my if statements are causing problems and can&a ...

Loading Java Script files in real-time

Is there a method to dynamically load JS files before "$(document).ready" is triggered, while still having them available in the ready event handler? Is there a feature in jQuery that allows for this process? The challenge I am facing involves loading di ...

Top-notch strategy for creating Node Package Manager packages that are interdependent

As we work on developing two React-based applications, let's call them app-a and app-b, we also manage two dependencies. One is a shared-components package, which contains components shared between the two applications, and the other is a shared-utili ...

What is the best way to iterate through an object and retrieve the following 3 items using a for loop in JavaScript

After fetching data from a website and storing it in a variable, I have successfully implemented a for loop that returns 3 properties from the object every time a button is clicked. However, the issue arises as the same data is returned with each button c ...

How can I retrieve my array state in a different router page using VUEJS and VUEX?

I have created a page with two routes - one for the home page and another for the configuration where users can decide what content should be displayed on that container. In the configuration panel, I was able to retrieve input values and stored them in my ...

Guide for preventing hours before the scheduled date and time with v-calendar

I am utilizing v-calendar to display the start date and time as well as end date and time in dateTime mode. My goal is to prevent the end date and time from being set before the start date and time. In order to achieve this, I have implemented the :min-dat ...

What are the steps to configure MongoDB on Heroku using MongoHQ and Node.js?

I am currently using a local application, which is what I'm most familiar with. Heroku provided the following snippet of code: var mongo = require('mongodb'); var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || &apos ...

Can you please explain the distinction between angular.equals and _.isEqual?

Do these two options offer different levels of performance? Which one excels at conducting deep comparisons? I've encountered situations where Angular's equals function fails to detect certain differences. In addition, I've observed that th ...

Steps to store user input into an array and subsequently combine the stored input:

I am currently working on a form that consists of two text boxes: Task and Description. My goal is to be able to log the input from both boxes and save it via a submit button. For example: Task: do laundry Description: do a buttload of laundry (idk lol) I ...

Performing an asynchronous request within a dynamic helper (or a suitable substitute) in Express version 2.x

I'm attempting to display the total message count for a user's inbox on my website's layout. I initially thought of utilizing Express' dynamicHelpers to achieve this, but in versions of Express <= 2.x, these helpers do not support as ...