¿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

Issue: It seems like there is an error with using functions as a React child. Uncertain about the exact location

This specific issue is one of the two errors I have come across in the same application referenced in my previous inquiry. The first error encountered is as follows: Warning: Functions are not valid as a React child. This may occur if you mistakenly return ...

Detecting letter case and text input in an HTML form can be done by using

I am looking to format a question along with multiple options in a text box, similar to how it is done in a Word file or plain text. Once saved, I want the questions to be displayed in a list and the options organized in a table. How can I extract the ques ...

Sharing data from AJAX calls in Vue using vue-resource

After using Vue resource, I'm attempting to create an AJAX call that is based on the data received from a prior AJAX call. I have successfully bound the data fetched from /me to the userDetails prop. However, when trying to pass userDetails.id into t ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Using various hues for segmented lines on ChartJS

I am working with a time line chart type and I want to assign colors to each step between two dots based on the values in my dataset object. In my dataset data array, I have added a third item that will determine the color (if < 30 ==> green / >30 ==> red ...

Tips for utilizing regex to locate words and spaces within a text?

I'm feeling so frustrated and lost right now. Any help you can offer would be greatly appreciated. I am currently dealing with an issue in Katex and Guppy keyboard. My goal is to create a regex that will identify the word matrix, locate the slash that ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Using Regular Expressions for Validation

As a designer trying to set up a payment page without strong developer skills, I've hit some roadblocks. The payment company gave me guidance that involved using regular expressions for validating the 'AMOUNT' field, but my attempts to modif ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

What makes using setInterval with a self-invoking function a smarter choice?

I recently came across an explanation on how to properly use the setInterval() function. Essentially, it was mentioned that (function(){ // perform some actions setTimeout(arguments.callee, 60000); })(); ensures that the subsequent call from setTim ...

Remove the most recently played sound from an array of sound using Vue.js

I've been trying to figure out how to randomize the sounds that play when a button is clicked, but I also want to avoid repeating the last played sound. It just doesn't sound right if the same sound plays repeatedly in quick succession. I'm ...

Is it possible to scroll a div on mobile without the need for jQuery plugins?

Upon investigating the initial query, we managed to implement D3js for identifying a scroll event. This allowed us to scroll the div #scroll-content from any location on desktop devices. However, we encountered an issue where this method does not function ...

Is it accurate to consider all JavaScript code and variables as inherent properties of an execution context?

It's worth considering that everything in JS code can be viewed as a property of an execution context, whether it's a global, function, or eval() execution context. Why is this the case? Each execution context has its own unique lexical and v ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

Using React Router can sometimes lead to an issue where the React components are

My server side rendering is set up for performance, but I am encountering discrepancies between the client and server renderings. The client initially renders <!-- react-empty: 1 --> instead of components, which leads to a different checksum. As a re ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...

The process of efficiently uploading a batch of images to Firebase storage while also obtaining all the respective

I have been using firebase storage to upload images and save their respective URLs in the firebase database. However, I recently encountered an issue with my code. In firebase v8, everything was working fine, but after updating to version 9, the following ...

Puppeteer: Easier method for managing new pages opened by clicking a[target="_blank"]; pause for loading and incorporate timeout controls

Overview I'm seeking a more streamlined approach to managing link clicks that open new pages (such as target="_blank" anchor tags). By "handle," I mean: fetch the new page object wait for the new tab to load (with specified timeout) Steps to r ...