What is the best way to combine arrays?

Here is the array retrieved from the database:

[
    {
      "_id": "58144e6c0c8d7534f4307269",
      "doctor_id": "5813221ace684e2b3f5f0a6d",
      "prescription": [
        {
          "_id": "58144e6c0c8d7534f430726a",
          "medicine_id": "10011241343"
        }
]

I would like to merge it with a new prescription entry as follows:

[
    {
      "_id": "58144e6c0c8d7534f4307269",
      "doctor_id": "5813221ace684e2b3f5f0a6d",
      "prescription": [
        {
          "_id": "58144e6c0c8d7534f430726a",
          "medicine_id": "10011241343"
        },
      "prescription": [
        {
          "_id": "58144e6c0c8d7534f430726a", // this should be autogenerated
          "medicine_id": "10011241344"
        }
]

What is the correct way of achieving this?

I attempted the following approach:

var arr = data.presription
arr=req.body// where req.body contains only medicine id

Followed by:

dbModel.user.findById(data._id, function(err, data) {    
    data.prescription = arr;
    data.save(function(err) {
        if (err) {
            res.status(202).json({
                "success": "0",
            });
        } else {
            res.status(200).json({
                "success": "1"
            });
        }
    })
});

However, the result is not as expected. How can I correctly accomplish this task?

Note: When using console.log(arr), only the old data is being displayed.

Answer №1

Initially, data.presription is defined as an array.

data.presription.push( {
    "_id": "58144e6c0c8d7534f430726a",
    "medicine_id": "10011241344"
});

It's important to note that this action does not involve merging two arrays, but rather appending new items to the existing array.

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

Having trouble accessing an AngularJS $scope variable because it is coming up as undefined

Currently, I am developing an Electron application using AngularJS for the frontend. Since node.js operates at the OS level while Angular runs at the client level, communication between the two is achieved through IPC (Inter-Process Communication) implemen ...

Struggling to link an external JavaScript file to your HTML document?

While attempting to run a firebase app locally, I encountered an error in the chrome console: GET http://localhost:5000/behaviors/signup.js net::ERR_ABORTED 404 (Not Found) Do I need to set firebase.json source and destination under rewrites or add a rout ...

Switching from HTTP to HTTPS with Express and Heroku

Despite Heroku's suggestion to use NPM packages, I've had no luck finding one that successfully forces SSL for express apps. The only solution that seems to work is the following, but it angers Google. Question: Can anyone provide a reliable met ...

Step-by-step guide on deploying an Angular and Express project to Google App Engine

I am in the process of deploying my app to Google App Engine. I have already set up App Engine and installed gcloud on my local machine. While I have been successful in deploying some projects, I have only done so for Angular applications. My goal now is ...

PHP array is not being successfully converted to JSON format on an online JSON editor

After printing this PHP array using print_r(), I have the following data: Array ( [title] => Atle [code] => ATL [classroom] => traditional [start_time] => 06:00 AM [end_time] => 08:00 AM [grp_day] => Array ...

Tips for running a post-installation script when deploying an Angular 4 application to an Azure website using KuduScript

I recently faced an issue with my angular4 app deployed on azure web app (website) using Deployment Options through the Portal. To customize the deployment script, I utilized kuduscript [kuduscript -y –node] and modified deploy.cmd to specify how Azure s ...

"Using PHP to encode an array into JSON format might result in additional

My PHP array needs to be printed as clean JSON, but I'm encountering issues with extra quotes. While the current JSON output is technically valid, it's not formatted how I want it to be. Below you can see the original PHP array, the json_encode o ...

Find the difference between array_A and the documents in array_B using MongoDB's $match operator, and return the result as Array_C

I need to create an array_C that includes only the elements from array_A that are not present in array_B. My approach involves using $match in aggregate to specify array_B. For instance: array_A = [1, 2, 3] array_B = [2, 4, 6, 8, 10] array_C = [1, 3] I a ...

Is there a permanent solution to fixing the error code -4094 that is repeatedly occurring during React Native startup?

When attempting to execute react-native start, an error occurred which has not been encountered before. The error message is as follows: ERROR ENCOUNTERED Loading dependency graph...events.js:287 throw er; // Unhandled 'error' event ...

I received a "quota exceeded" message from Mongolab, even though I had only used up half of my allotted storage space

I have set up a Sandbox database for an amateur project that I am working on for a competition. This is my first time doing something like this, and unfortunately, I made the mistake of waiting until the very end to upload all the records I need for analys ...

Having difficulty upgrading NPM on Ubuntu Server version 16.04

I am facing an issue while attempting to update NPM on my Ubuntu Server (16.04) as the upgrade process is not working correctly. npm -v displays 3.5.2 After executing sudo npm install npm@latest -g The output is as follows: /usr/local/bin/npm -> ...

Understanding the Flow of Parameters in Express Validator Functions

I am wondering about how the parameters are passed to the validator middleware. This snippet is extracted from express-validator. For instance, the parameter programming_language is passed to the check() function. const { check, oneOf, validationResult ...

Next.js for the server-side

Today I decided to dive into learning NextJs (React) in order to create a small website for my family. As I progressed through the tutorials on NextJs, it dawned on me that the framework does not natively support server-side rendering, meaning I will need ...

I encountered a mapper_parsing_exception while attempting to connect Elasticsearch to my Node application using Mongosastic

Hello, I am currently working on integrating elastic search into my NodeJS project and encountering the following error: { Error: [mapper_parsing_exception] No handler for type [string] declared on field [category] status: 400, displayName: 'BadRequ ...

What is the best way to identify a specific pattern within a string using regular expressions in JavaScript?

Looking for a way to extract specific values from a string? let temp = 'Hi {{username}}, Your request with request id: {{requestId}} has been processed. Please contact your nearest shop.' Desiring an array like this from the string: ['user ...

Template not found: Error encountered in nodemailer-express-handlebars: ENOENT: The specified file or directory does not exist in the node

I've been attempting to utilize nodemailer and express-handlebars in my node.js application to send a template form. However, I keep encountering the "no such file" error. Unfortunately, I have no clue what I'm overlooking or missing. Here is m ...

Tips for executing a .exe file in stealth mode using JavaScript?

I am currently working on the transition of my vb.net application to JavaScript and I am facing a challenge. I need to find a way to execute an .exe file in hidden mode using JS. Below is the snippet from my vb.net code: Dim p As Process = New Pro ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

What are the steps to set up Redis Store in my production environment?

I am currently in the process of setting up Redis as a session store, but for some reason it's not functioning properly. I have integrated passport.js and express-flash, however when I attempt to run the current Redis setup, it fails to work: var ses ...

Finding the measurement of a sofa using couch.get(data, headers, status)

After attempting to set up a node.js application with express.js by connecting to couchdb, I utilized the npm package called nodejs-couch. app.get('/', function(req, res) { couch .get(dbName, viewUrl) .then( function(data, heade ...