¿What is preventing me from merging two arrays within this query handler?

I'm facing an issue while trying to merge arrays from a request with existing arrays in a MongoDB database. Despite my attempts, the arrays do not seem to be merging as expected. Can anyone help me identify what might be causing this problem?

router.post('/add-publication-data', async (req, res) => {
    try {
        const publication = await Publications.findOne({ _id: req.body._id });
        publication.toObject();
        publication.additionalauthors.concat(req.body.additionalauthors)
        publication.students.concat(req.body.students)
        console.log(publication.students)
        publication.institutions.concat(req.body.institutions)
        publication.keywords.concat(req.body.keywords)
        publication.highlights.concat(req.body.highlights)
        publication.save()
            .then(
                data => {
                    res.json(data);
                })
            .catch(e => {
                res.json({
                    message: e
                });
            });
    } catch (err) { console.log(err); res.json({ message: err }) };
});

Answer №1

Using the Concatenation Method

The behavior you are experiencing with the concat method is expected. According to the MDN documentation:

The concat() method merges two or more arrays without altering the original arrays, creating a new array instead.

To obtain the merged array, make sure to assign the result back by making this change:

publication.additionalauthors.concat(req.body.additionalauthors)

Replace it with:

publication.additionalauthors = publication.additionalauthors.concat(req.body.additionalauthors)

Utilizing the Push Method

An alternative approach is to utilize the push method

By using the push() method, you can add one or more elements to the end of an array and receive the updated length of the array.

publication.additionalauthors.push(...req.body.additionalauthors)

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

New and Improved: Node.js Integration for Handling POST Requests with Rally's Latest API Authorization Version 2.0

After setting up a Node.js server to handle Rally POST requests, everything was working perfectly until I made the switch to the new Rally v2.0 API. The updated authorization model has left me scratching my head on what changes I need to make to my serve ...

Getting values from a list within a JSON object using Python and MongoDB - step by step guide

My MongoDB database has the following structure: "addr1": { "hostname": { "-name": "x" }, "os": { "-version": "x", "-acc": "x" }, "ports":{ "PORTNUMY" : { "service": "x", "version": "x" }, "PORTNUMX" : { "service": "s", "ver ...

Nodejs functions properly on a local machine, however, it encounters issues when deployed on a VPS

My nodejs/javascript code seems to be running fine on my local pc, but when I try to run it on my vps, it's not working properly. Even though I have the same node_modules installed and the code is identical. Here's a snippet of my code for refere ...

Check if the content key Json exists by implementing Vue

Can anyone help me with checking the existence of "novalue"? For instance: { name: "maria", city_id: "novalue" .... } What would be the best way to do this in Vue? Should I use <div v-if="condition"> or a function? ...

JavaScript does not recognize Bootstrap classes

I am utilizing Bootstrap 5.3.0 and have included it through CDN links in my JS script. This is how I am injecting it using my js file within the existing website's DOM via a chrome extension named Scripty, which serves as a JS injector extension for c ...

Exploring the possibilities of comprehensive root level routing in Express.js: factors to consider and strategically planning for future route expansion

I'm currently working on a Node web app using Express.js (3.0), and I want to ensure that my URLs are clean and user-friendly. Specifically, I'd like the user profiles to be accessed through domain.com/username, and for each user-created page to ...

Show only relevant dropdown options when a radio button is selected, and also automatically adjust options when the page

I am working on a form that includes radio buttons and a dropdown list. If the user chooses 'girls', I need to display only caroms and chess, which are specified in the girlsGames variable. If the user selects boys, I want to show the dropdown ...

Node.js middleware for verifying authentication with dynamic variables

Before rendering a website, I need to verify if the user is authenticated and of a certain type. The middleware function for this purpose is as follows: function isAuthenticated(req,res,next,required_type){ if(Parse.User.current()){ Parse.User.current ...

How to selectively filter an array of objects using another array in JavaScript

Imagine you have an array filled with objects: people = [ {id: "1", name: "abc", gender: "m", age:"15" }, {id: "2", name: "a", gender: "m", age:"25" }, {id: "3 ...

Next.js presents a challenge with double-language applications

I am currently in the process of developing a web application using Next.js that will cater to users who speak my native language and English. I have a specific approach in mind: First, I plan to create a folder: /pages/en-us pages/ |--(all app pages) |- ...

Restricting data list values in AngularJS

Currently, I am facing a performance issue while trying to display approximately 2000 values retrieved through an API call using DataList in AngularJS. The page becomes extremely slow due to the large number of items being rendered. Is there a way to optim ...

Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays. $scope.arr1 = [ { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d717 ...

Incorporating a setup file into my JavaScript project

In my JavaScript project, I have both frontend and backend codes (NodeJS). Here is the folder structure for my production environment: /prod /server sourceCode1.js sourceCode2.js ... sourceCodeN.js index.js ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

The functionality of the d3 Bar chart with a tool tip seems to be malfunctioning

Working on a D3 svg chart with built-in tooltips using the d3-tip library. Check out the original code here. Utilizing Django as the back end to populate log count per year from datetime. Successfully populated axis and labels except for the bars. Here i ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

EJS include function not working properly

In most cases, my EJS pages include the code below: <%- include('elements/fbviewpagepixel.ejs') %> Everything runs smoothly except for one particular page where I encountered an error message stating include is not a function. I managed t ...

Is it possible to dynamically assign and call functions through an Object in Angular 6?

I implemented a click handler for a button that is generated dynamically. Within the click handler function, I am invoking a callback function. However, I encountered an issue where an error message popped up stating that "Callback function is not a fu ...

What are the reasons for the dynamic exclusion of an element in Angular?

Can someone help me figure out why my data is not being added dynamically using ng-repeat? I have entered the "name" which should be added to the data, but it is not displaying in the UI. You can see the issue in this demo app.controller("studentcntr", ...

Tips for obtaining the dynamically loaded HTML content of a webpage

I am currently attempting to extract content from a website. Despite successfully obtaining the HTML of the main page using nodejs, I have encountered a challenge due to dynamic generation of the page. It seems that resources are being requested from exter ...