What could be the reason for this code not changing the original array? Illuminate Express API

I encountered a strange issue while working on an Express API. I need to retrieve a list of posts from the MongoDB database and then add a new property to each post object before returning it to the client.

Despite my efforts, I am not able to successfully add the newProperty as intended. The list of objects retrieved from the database remains in their original state without the additional newProperty attached to them.

What could be causing this problem?

Here is the code snippet:

exports.fetchPosts = async (userID) => {
    // Fetch posts of user's friends and the user himself
    try {
        // Get friend's posts
        const friends = await User.findById(userID).select('friends');
        const allPosts = [];
        for (let i = 0; i < friends.friends.length; i++) { // For each friend
            // Retrieve each friend's posts
            const posts = await Post.find({ author: friends.friends[i] }).populate('author', 'username');
            posts.forEach(friendPost => {
                friendPost.newProperty = 'newProperty';
                allPosts.push(friendPost);
            });

        } catch(err){ console.log(err)}
    }

Answer №1

Include newProperty

If you're not seeing the new post data you expected, it might be a bit confusing to figure out what exactly you're after. Try running this snippet to see if it clarifies things for you. Also, I noticed that your catch statement was out of scope, so I made sure to correct that as well.

const fetchPosts = async(userID) => {
  // Fetch posts of users' friends and the user himself
  try {
    // Get friends' posts
    const allPosts = [{
        userID: 1,
        author: 'jack',
        username: 'jackStack',
        friends: ['bob'],
        content: '',
      },
      {
        userID: 2,
        author: 'bob',
        username: 'bobby',
        friends: ['jack'],
        content: '',
      },
    ];

    // Comment out my line and uncomment yours when done testing
    const friends = {
      friends: ['jack']
    };
    //const friends = await User.findById(userID).select('friends');
    for (let i = 0; i < friends.friends.length; i++) {
      // For each friend
      // Get each friend's posts
      // Comment out my line and uncomment yours when done testing
      const posts = [{
        author: 'jack',
        username: 'jackStack'
      }];
      //    const posts = await Post.find({ author: friends.friends[i] }).populate('author', 'username');
      posts.forEach((friendPost) => {
        friendPost.newProperty = 'newProperty';
        allPosts.push(friendPost);
      });
    }
    // Make sure to return an answer with async 
    return allPosts;
  } catch (err) {
    console.log(err);
  }
};

/*
 * * Comment out if you are done testing results 
 */
(async() => {
  console.log(await fetchPosts(2));

  // [object Array] (3)
  //[// [object Object] 
  //{
  //  "userID": 1,
  //  "author": "jack",
  //  "username": "jackStack",
  //  "friends": [
  //    "bob"
  //  ],
  //  "content": ""
  //},// [object Object] 
  //{
  //  "userID": 2,
  //  "author": "bob",
  //  "username": "bobby",
  //  "friends": [
  //    "jack"
  //  ],
  //  "content": ""
  //},// [object Object] 
  //{
  //  "author": "jack",
  //  "username": "jackStack",
  //  "newProperty": "newProperty"
  //}]
})();

// Uncomment when not testing
//exports.fetchPosts;

Codepen

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

Combine multiple form values to calculate the total sum

To tackle the issue of adding up independent totals in a PHP foreach loop and displaying a grand total, we need to modify the JavaScript function. Right now, the function works fine for each line, but doesn't calculate the grand total correctly. Let&a ...

When the page is scrolled to 50 pixels, a modal pop-up will appear

I attempted to use cookies to store a value when the user clicks on a popup to close it, ensuring that the popup does not show again once closed. However, I am encountering an issue where the popup continues to open whenever I scroll, even after closing it ...

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

The router makes a call to passport.serialize, but it fails to run the

When using Node, Express, and Passport, I have successfully logged users in and serialized the session as shown below: passport.serializeUser(function(user, done) { done(null, user.id); }); // Deserializes the user session after a reques ...

Is it possible for Node.js to execute individual database operations within a single function atomically?

As I delve into writing database queries that operate on node js, a puzzling thought has been lingering in my mind. There seems to be a misunderstanding causing confusion. If node is operating in a single-threaded capacity, then it follows that all functi ...

Having trouble initializing a variable in a function and accessing it from a separate function

Currently, I am executing a node js file which is receiving a post request as shown below. app.post('/', function (req, res) { var firstLine = req.body.firstLine; var secondLine = req.body.secondLine; var previewID = req.body.preview ...

Error encountered while retrieving : [errorCode]: HTTP code error [statusCode]

dioerror [dioerrortype.response]: http status error [statusCode] These are the Headers: Headers("Authorization": "token", "Content-Type" : "multipart/form-data", "Accept" : "application/json") These are the Data attributes: try { ...

Polyfill for window.showOpenFilePicker function

Could anyone recommend a polyfill for the window.showOpenFilePicker method? For reference, you can check out the documentation on MDN. ...

Assistance with Blackberry Webworks (Widget) JavaScript & XML/JSON Integration

Let me paint you a picture... I am in the process of crafting a Blackberry WebWorks (widget) that serves as a gateway to an external website. The majority of the pages reside on this remote site, with the exception of a user customizable homepage where us ...

Exploring the Power of ReactJS Source Mapping

After adding the .env file to my react project, I noticed that when the project is uploaded to the server, the console source is displaying all components. Although I added the .env file and included the following code: GENERATE_SOURCEMAP = false; The i ...

There appears to be an error in Firestore: TypeError - Firestore's db.collection(...).document function is

I am encountering an issue with my script where I believe I am correctly pointing to the firestore() database instead of the realtime database. Despite successfully adding data to the firestore() database in another route, I am now receiving an error when ...

Refreshing an iFrame in NextJS from a different component

I am working on a NextJS application that includes a specific page structure: Page: import Layout from "@/components/app/Layout"; import Sidebar from "@/components/app/Sidebar"; export default function SiteIndex() { return ( < ...

Dealing with CORS policy challenge

I am encountering an issue with Access to XMLHttpRequest at 'http://demo.equalinfotech.com/Iadiva/images/product/1634623781ladiva_barbara_01.glb' from origin 'http://localhost:8100' being blocked by CORS policy due to the absence of the ...

The object3d.translateZ function in Three.js is resulting in unexpected NaN values for all position properties

I'm encountering an issue where the use of translate[X|Y|Z] on my object results in its position becoming distorted and only displaying NaN values. Using Three.js r70 The relative position differs from the absolute position: Snippet from my code i ...

Save the list of arrays into a designated variable

I am struggling to save the array list in a variable and I'm not sure how to go about solving this issue. The xpath query successfully retrieves a list of items, which are being displayed in the console without any problems. However, I am unable to f ...

Managing table row associated javascript (control ID) when cloning the row can be achieved by properly updating the control IDs in

At first, the table only contains one tr (label/header). Upon clicking the add button, a new tr is created which will then be cloned upon subsequent clicks of the add button. <tr> <script type="text/javascript"> //fetching the value ...

React does not allow for images to be used as background elements

I am currently working on a web page and I have attempted to use both jpg and png images as backgrounds, but they do not seem to display on the page. import './Entrada.css' const Entrada = () => { return( <div style={{ b ...

Sorting tables with jQuery UI sortable() and rowspan功能

Can jQuery UI's sortable() be configured to sort rows based on their "containing" element only? I have a table with rowspanned cells that should only be sorted within their respective spanned columns. var $sortable = $('.nested-sortable tbody&ap ...

Transmitting Data via Socket.io: Post it or Fetch it!

I am struggling to send data via POST or GET in socket.io without receiving any data back. My goal is to send the data externally from the connection. Take a look at the code snippets below: Server-side code: app.js io.sockets.on('connection', ...