Refresh information and establish connections between new objects - Sequelize

I have developed a function within my Express route that is responsible for updating user information as well as their assigned role. The role itself is represented by another Sequelize Object, and I have established a one-to-many relationship between the two:

User.belongsTo(Role);
Role.hasMany(User);

Within my route, this is how the updatefunction is structured:

const UpdateUser = async user => {
    if (Object.keys(user).length !== 0) {
        const { id, firstName, lastName, phone, email, role } = user;
        let modUser = await User.findOne({ where: { id }, include: [{ model: Role}] });
        if (modUser.firstName !== firstName) modUser.firstName = firstName;
        if (modUser.lastName !== lastName) modUser.lastName = lastName;
        if (modUser.phone !== phone) modUser.phone = phone;
        if (modUser.email !== email && UniqueEmail(email)) modUser.email = email;
        if(modUser.Role.id !== role) {
            await modUser.setRole(await Role.findByPk(role));
        }
        modUser.save();
        modUser = await User.findOne(
            {
                where: { id },
                include: [{ model: Role}],
                attributes: { exclude: ['RoleId', 'password'] }
            },
        );
        return modUser.reload();
    }
    return { error: "No user found" };
}

Although the function successfully updates user information and role in the database, there seems to be an issue with the returned User occasionally not reflecting the updated details but rather showing previous information. I am uncertain whether my implementation is incorrect, or if attempting to simultaneously update the User model and assign a new Role may be causing a conflict.

Any insights on how to resolve this? Thank you!

Answer №1

It came to my attention that many functions in sequelize operate asynchronously... I overlooked the importance of using the await keyword to ensure that asynchronous tasks are completed before proceeding.

await user.update();
await user.delete();

Credit goes to @Heiko TheiBen for pointing this out.

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

Certain websites are experiencing issues with loading the Vimeo player

Encountering a puzzling issue - Vimeo's javascript player API is defined on some websites, but undefined on others. To test this out, you can go to StackOverflow and open the javascript console, then paste in: jQuery.getScript('https://player.v ...

Instructions on uploading a PDF file from a Wordpress page and ensuring the file is stored in the wp-content upload directory folder

What is the process for uploading a PDF file on a WordPress page? <form action="" method="POST"> <input type="file" name="file-upload" id="file-upload" /> <?php $attachment_id = media_handle_upload('file-upload', $post->I ...

What is the measure of randomness created by Math.random?

I am trying to create a large random number without the need for cryptographic security. Therefore, I have opted not to use crypto.getRandomValues. Currently, my method of generating the random number is as follows: const random = length => Math. ...

The Vue DevTools are functioning as expected, but there seems to be an issue

Encountering a peculiar issue where the value displayed in Vue DevTools is accurate, matching what is expected in my data. When I first click on the "Edit" button for an item, the correct value appears in the browser window as intended. However, upon clic ...

Does the Express Router load partial paths?

Only one route is currently defined with the path: :page?/:pagination? Both page and pagination are optional in this path. When I enter the path /test in my browser, it still returns the result of the first route. How can I resolve this issue? ...

Searching strings with regex

I am working with a specific string of text that I want to replace within a given div. Here's how I know to do it: myelement.replace(/foo/g, 'bar'); But what if I need to use my own string instead of the fixed text "foo"? myelement.replac ...

How should one go about organizing the JavaScript code for a complex application?

Imagine you are working on a complex project with extensive use of JavaScript throughout the site. Even if you divide the JavaScript into one file per page, there could still be around 100 JavaScript files in total. What strategies can you implement to ma ...

Creating a Delicious Earth Progress Pie

I'm looking to incorporate a unique progress bar design on my website, similar to this one: The progress pie Can anyone guide me on how to create a progress pie with an image inside it that changes color as it moves? ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

What is the best way to retrieve information from a webpage I have created using an express backend and an HTML frontend

I designed a login page named index.html that prompts users to enter their email and password, followed by a submit button with the label "Log In": <input type="submit" value="Log In" id="loginbutton"> Within my app.js ...

Guide on authenticating WCF rest service in node js

I encountered an issue while attempting to call a WCF rest service within a nodejs API. The error 401: unauthorized is thrown, despite providing correct credentials. Interestingly, the same credentials work when calling the service through SOAP UI. Below ...

onTouch event causing problems with gesture scrolling

Currently, I am utilizing the following Javascript code to implement ontouchstart/move/end callbacks on div elements in an iOS web application. The issue I am facing is that when attempting to scroll through the page, it triggers the ontouchstart event and ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

What is the method for calculating the total number of votes in a review, and subsequently determining the average?

So I've encountered a situation where I'm working in a Vue context with Laravel as the backend. On my homepage, I have a select option for searching musicians based on their genre. Now, when I navigate to this page, I want each musician card to d ...

Is there a way to dynamically assign self-referencing onClick events to a table of buttons?

Just delved into the world of JavaScript and now I'm facing a challenge. I've used JS to create a table of buttons, which translates to this HTML: <table border="1" style="width: 100%; border: none;"> <tr> <td class="emptyBord ...

Utilize date-fns to style your dates

Struggling to properly format a date using the date-fns library. The example date I'm trying to work with is 2021-09-20T12:12:36.166584+02:00. What am I doing wrong and what is the correct approach? Here's the code snippet I have so far: import ...

Guide to creating a reminder feature in NestJS

In my NestJS project, I've created a POST API to add a Date object representing the date and time for sending notifications to a mobile app. Currently, I am working on checking which reminders have been reached for all users in order to trigger remin ...

The HTML collection structure remains consistent across all web browsers

Using document.getElementsByTagName() to search for elements results in a HTMLCollection. If the elements have ids, then the output will include elements with both an index and an id. The question arises: Will this structure remain consistent across all b ...

React is failing to display identical values for each item being mapped in the same sequence

I have implemented some standard mapping logic. {MEMBERSHIPS.map((mItem, index) => ( <TableCell className="text-uppercase text-center" colSpan={2} padding="dense" ...

Create a JSON array from a collection using Backbone.js

I have a collection called Platforms in my backbone framework. The structure of this Platforms collection is organized as follows: Platforms PlatformList models 0: Platform attributes id: 1 name: "some name" 1 ...