Unable to figure out why information is not being transferred to an array through Mongoose

Seeking assistance as I am unable to figure out how to place a set of information into an array named "teamDetails". Here is the relevant /post item from server.js:

app.post('/create', (req, res) => {
    console.log('Post command received');
    console.log(req.body);
    console.log(req.body.data.teamDetails[0]);
    //Need to push 'teamDetails' variable as an object into an array of the same name
    var teamDetailsObj = {
    // Modified for Postman
    "teamName": req.body.data.teamDetails[0].teamName,
    "teamNameShort": req.body.data.teamDetails[0].teamNameShort,
    "teamfounded": req.body.data.teamDetails[0].teamFounded,
    "teamHome": req.body.data.teamDetails[0].teamHome
    };
    console.log(teamDetails);
    var newTeam = new Team({
        "data.added": new Date(),
        "data.entry": req.body.data.entry
    });

    newTeam.save().then((doc) => {
        console.log("This is newTeam.data: " + newTeam.data);
        console.log("This is teamDetailsObj: " + teamDetailsObj);
        newTeam.data.teamDetails.push(teamDetailsObj);
        var teamId = doc.id;
        res.render('success.hbs', {teamId});
        console.log("Team Added - " + teamId);
    }, (e) => {
        res.status(400).send(e);
    });
});

Here is my team.js model:

var mongoose = require('mongoose');
var ObjectID = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var Schema = mongoose.Schema;

var Team = mongoose.model('Team', {
  data: {
    entry: {
      type: String,
      default: "USER.INPUT"
    },
    added: {
      type: Date,
      default: Date.Now
    },
    teamDetails: [
      {
        teamName: {
          type: String,
          trim: true,
          required: true,
          default: "First Team"
        },
        teamNameShort: {
          type: String,
          trim: true,
          uppercase: true,
          maxlength: 3,
          required: true
        },
        teamFounded: {
          type: Number,
          maxlength: 4
        },
        teamHomeCity: {
          type: String
        }
      }
    ]
  }
});

module.exports = {Team};

Lastly, the sample data being sent via Postman:

{
    "data": {
        "entry": "Postman.Entry",
        "teamDetails": [
            {
                "teamName": "Test Teamname",
                "teamNameShort": "TTN",
                "teamFounded": "1986",
                "teamHome": "London",
                "players": [
                    {
                    "player1Name": "Test Player 1",
                    "player1Position": "Forward",
                    "player1Nationality": "GBR"
                    },
                    {
                    "player2Name": "Test Player 2",
                    "player2Position": "Defender",
                    "player2Nationality": "UKR"
                    },
                    {
                    "player3Name": "Test Player 3",
                    "player3Position": "Goaltender",
                    "player3Nationality": "IRL",
                    "captain": true
                    }
                ],
                "coachingStaff": {
                    "headCoach": "Derp McHerpson",
                    "teamManager": "Plarp McFlarplarp"
                    }
                }
            ]
        }
}

(Note: players section not related)

The issue with the current code is that the resulting entry for teamDetails remains an empty array. Unable to push teamDetailsObj as expected.

Would appreciate any assistance provided. Thank you.

Answer №1

Seems like you are adding teamObjDetails after already saving it with newTeam.save().then( ... )

I am not too well-versed in Mongoose, but I can't see how the team details could exist if they were not added before saving.

Please inform me if this changes anything!

A. G

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

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

AJAX request: No values are being returned by $_GET

After spending hours trying to figure this out... I've been working on using AJAX to grab values from a jQuery slider within an <input> tag. The AJAX request is not failing (see code below), and when I use console.log to check the variable I&ap ...

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...

Installing a custom application structure/skeleton in Node.js using Express

Is it possible to save my frequently used app structure using the command line like this: express custom_build myapp Appreciate any help on this! :) ...

Unravel the encoded string to enable JSON parsing

Here is an example of my JSON string structure [{&#034;id&#034;:0,&#034;nextCallMills&#034;:0,&#034;delay&#034;:0,&#034;start&#034;:&#034;... I am facing an issue with JSON.parseString() Even after trying unescape() a ...

How to retrieve the value of input in a Formik form when the onChange event occurs

Currently, I am working on creating a form using React JS and the Formik library. One issue I encountered was related to validation, specifically the need to replace invalid letters with an empty string. str.replace(/\D/, ''); The challenge ...

Tips for handling the response after a view has been submitted on Slack using Bolt.js

Hey there! I added a simple shortcut to retrieve data from an input, but I'm facing an issue after submitting the view. The response payload is not received and the view doesn't update to give feedback to the user. Check out my code below: const ...

Store the results in the database following the execution of a protractor test

I am completely new to angular protractor testing. I have created some test cases using the protractor framework with jasmine runner BDD style. Within a single test class, I have 10 to 12 specs, each with an expectation. Currently, I am running these tests ...

When a base html tag is dynamically added, the browser mistakenly loads assets twice

When managing relative paths on a website, I utilize the <base> tag within the <head> section of each page. Although all resources loaded via relative-like paths in the documents are displayed correctly, my observations show that browsers such ...

Unable to handle a POST request initiated by an HTML Form

Recently, I started working with Express and Bootstrap. While attempting to create a login form that triggers a POST request to the server, I encountered an issue where the page displays "The page isn't working" instead of loading a new HTML page. He ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...

Utilizing jQuery to update dropdown selection based on JSON object values

In my JSON value, I have the following roles: var roles = { "roles":[ {"role_id":2,"role_name":"admin"}, {"role_id":4,"role_name":"QA"}, {"role_id":3,"role_name":"TL"}, {"role_id":5,"role_name":"user"}, {"role_id":1,"role_name":"r ...

Passing props in VueJS is a common task, especially while redirecting to another

I am working with two separate single-file components, each equipped with its own named route. In the Setup.vue component, there is a basic form that gathers and sends data to the Timer.vue component which expects certain props. Is there a way to navigate ...

Passing data between pages in Node.js/Express without disrupting the flow of RESTful routing

Within my Express app, the initial landing page prompts visitors to input their email address and then choose between "Sign Up" or "Log In", depending on whether they have an existing account. Following this input, users are directed to either "/signup" o ...

What is the best way to display a placeholder instead of the state's value when a page loads?

I'm having trouble displaying the placeholder of an input instead of its state value. When the page loads, it shows an empty select box because the testType state is null initially. How can I make sure that only the placeholder is shown instead of the ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

The justify-between utility in Tailwind is malfunctioning

Can someone help me figure out how to add justify-between between the hello and the user image & name? They are in different divs, but I've tried multiple ways without success. I'm fairly new to this, so any advice would be appreciated. This ...

"Enhance your data visualization with Highcharts Windbarb and effortless AJAX data

Alright. Let's rephrase a question that hasn't been answered yet. I've got a chart below with data loading dynamically via ajax. A simplified version (without ajax) of this graph works well as shown in this jsfiddle. The code below represe ...