You cannot add properties to an object within an async function

I am attempting to include a fileUrl property in the order object within an async function, but I am unable to make it work properly.

My expectation is for the order object to contain a fileUrl property once added, but unfortunately, it does not seem to be working as expected.

    router.get('/my-orders/:id', isAuth, async (req, res) => {
    const id = req.params.id;

    try {
        const orders = await Order.find({ userId: id });
        if (orders.length > 0) {
            for (const order of orders) {
                const getObjectParams = {
                    Bucket: bucketName,
                    Key: order.fileName,
                }

        
                const command = new GetObjectCommand(getObjectParams);
                const url = await getSignedUrl(s3, command, { expiresIn: 3600 });
                // adding fileUrl property to order
                order.fileUrl = url;
                
                // it logs only order without fileUrl property
                console.log(order);
            }

            res.send('OK');
        }
    } catch (error) {
        console.error(error);
    }
})

Answer №1

When working with MongoDB, it's important to remember that iterating through a cursor returned by Order.find() will provide you with MongoDB documents, not plain Javascript objects. If you need to work with plain Javascript objects for manipulation purposes, you can utilize the .toObject() method on the document.

router.get('/my-orders/:id', isAuth, async (req, res) => {
    const id = req.params.id;

    try {
        const orders = await Order.find({ userId: id });
        if (orders.length > 0) {
            for (const order of orders) {
                const getObjectParams = {
                    Bucket: bucketName,
                    Key: order.fileName,
                }

                const command = new GetObjectCommand(getObjectParams);
                const url = await getSignedUrl(s3, command, { expiresIn: 3600 });

                // Convert from MongoDB document to plain Javascript object
                const modifiedOrder = order.toObject();

                // Adding fileUrl property to order
                modifiedOrder.fileUrl = url;
                console.log(modifiedOrder);
            }

            res.send('OK');
        } else {
            res.send('No Orders Found');
        }
    } catch (error) {
        console.error(error);
        // Always send some response, even for errors
        res.sendStatus(500);
    }
});

Additionally, I've improved the request handler to ensure it always sends a response, whether there are orders found or any errors occur.


For more options and discussions, such as using .lean() and .set(), you can refer to this answer.

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

Creating a specialized filter for AngularJS or customizing an existing one

AngularJS filters are great, but I want to enhance them by adding a function that can check if a value is in an array. For example, let's say we have the following data: Queue = [ {'Name':'John','Tier':'Gold&ap ...

Tips for including subjects in JSON data

I am trying to include the subject in JSON data so that I can fetch it using $.each(data.subject). Below is my API code where I am retrieving all the data encoded in JSON format. Any assistance would be greatly appreciated. [{"id":"79","FirstName":"Elon", ...

The use of a script redirect in PHP can result in a recursive

Hey there, I'm a new rank newbie here! So I have this code that's supposed to redirect users to the relevant page on both mobile and desktop. But it seems like it's causing a never-ending loop with the webpage constantly reloading. Should I ...

Issue: Child Pages not found in Nuxt RoutingDescription: When navigating

Currently working on a Nuxt application that utilizes the WordPress REST API to fetch content. While my other routes are functioning correctly, I am facing challenges with nested pages. The structure I have implemented in my Nuxt app is as follows: pages ...

What is preventing the specific value in React state from being updated?

Starting off as a beginner, but I'm giving it a shot: In my React project, users input landing pages and I aim to extract data from these pages using JQuery and RegEx, then update the state with the extracted value. The issue I'm facing is that ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = { "@type": "Movie", "url": "/title/tt0443272/", "name": "Lincoln", "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA ...

Is there a way to utilize local resources in case CDNs are unable to load properly?

Encountering an issue with Bootstrap and jQuery loading from CDN, sometimes failing to import from the CDN source. For instance: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYii ...

Learn the Method Used by Digg to Eliminate "&x=0&y=0" from their Search Results URL

Instead of using a regular submit button, I have implemented an image as the submit button for my search form: <input id="search" type="image" alt="Search" src="/images/searchButton.png" name="" /> However, I encountered an issue in Chrome and Fire ...

Every time I switch views using the router in vue.js, my three.js canvas gets replicated

After creating a Vue.js integrated with three.js application, I encountered an issue with the canvas getting duplicated every time I opened the view containing the three.js application. The canvas remained visible below the new view, as shown in this image ...

Emulate the selection process using element-ui and vue-test-utils

During my unit tests using Jest and Element-ui in Vue, I encountered an issue with a component containing a select element with 2 options. After selecting an option from the dropdown, I needed to verify that a specific action was called. 1) Everything wor ...

The backbone module is experiencing formatting issues

I'm new to learning backbone.js. I've created the example below, but unfortunately, it's not functioning properly. Can someone please help me understand why? The goal is to simply display the name within my div element. (function($) { ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...

Using a variable in a Joomla module to create a JavaScript object with PHP

I am currently developing a Joomla module that features a progress bar utilizing the ProgressBar.js plugin. Since this module is designed to load multiple objects on a single page, hardcoding the IDs of these objects is not feasible. To address this, I uti ...

Facing challenges when running asynchronous mocha tests using async/await syntax

Working on E2E tests using mocha and selenium-webdriver has been quite a challenge for me. Although I have implemented async/await functions to handle most of the tests smoothly, I am facing an issue where none of the tests are completing successfully. Her ...

Pulling information from an iOS application to a MEVN application using a GET request

After successfully building a Vue.js Single Page Application with an Express/Node backend, I am now venturing into creating an iOS app that can interact with the same backend. When attempting to make POST requests from iOS (Xcode) to log in a user using A ...

Creating a Flot Bar Chart that displays non-stacking values

I am new to using Flot for creating charts. Currently, I have a bar chart displayed below: https://i.stack.imgur.com/RSumf.png Here is the code snippet I utilized to generate this chart: $.getJSON('chartBar.json', function(graphDataBar){ $ ...

AngularJS: Utilizing UI Bootstrap Popover with the Placement Set to 'bottom-right'

I am working with UI Bootstrap and AngularJS, attempting to customize a popover to have the 'bottom-right' placement instead of the default 'bottom' or 'right'. The desired functionality is illustrated in the image below. htt ...

Implementing Socket.IO in the front end

I am in the process of setting up a nodejs+express+socket.io server. Additionally, I have generated a scaffold for my frontend app using yeoman. The socket.io server is running on port 3000, while the yeoman scaffold http server is on port 9000. I succe ...

Is it possible to utilize EmberJS or other frameworks without the necessity of setting up its server?

I am in search of a JavaScript framework that offers the following features: MV* Well-structured HTML file as template Fast rendering (possibly using virtual DOM) Ability to combine and be compatible with other plugins or libraries Edit on tablet IDE app ...