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

Any tips on silencing webpack's constant nagging about the "Critical dependency: require function is used in a way..." warning message?

My immediate goal is to resolve this warning. However, it seems that a different approach may be necessary. I have developed an npm library for date/time functions with most of the code being general-purpose and compatible with both Node.js and web browse ...

Inability to submit page after clicking on lower half of button while eliminating validations

In my current Struts2 application, I am encountering a issue related to validations on textfields. The validations include checks for missing values and incorrect values. Below these fields, there is a button that should submit the form once all validation ...

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

Finding a solution for the restriction of fragment URLs with Google Redirect URIs

I develop a MEAN stack project using my Mac. The web pages https://localhost:3000/#/login and https://localhost:3000/#/new are functioning properly (note that the pages require /#/ in the URL to work). The https://localhost:3000/#/new page includes a butto ...

The performance of MongoDB is lagging due to the excessive number of documents,

5 million MongoDB documents: { _id: xxx, devID: 123, logLevel: 5, logTime: 1468464358697 } Indexes: devID My aggregation query: [ {$match: {devID: 123}}, {$group: {_id: {level: "$logLevel"}, count: {$sum: 1}}} ] Aggregation ...

Displaying an 'undefined' message in a JavaScript alert box

Hello! Just made the switch from C#/C++ to JavaScript recently and I'm really enjoying it. I've encountered a behavior that has me scratching my head, can anyone help explain? So here's what's happening: when I run this script, I see ...

Identifying patterns within a string using JavaScript and TypeScript

Given a user-input pattern, for example [h][a-z][gho], and a string "gkfhxhk", I am attempting to determine if the string contains the specified pattern. The pattern dictates that the first character must be 'h', followed by any letter from a-z, ...

Setting a JavaScript variable to null

Using Jquery, I have a variable that is assigned a value on button click. After the code executes successfully, I need to reset the variable to null. $("#btnAdd").click(function () { var myDataVariable= {}; myDataVariable.dataOne="SomeDa ...

Issue with Node.js xml2js module: Sitemap attributes are not being recognized during creation

Currently, my project involves utilizing node.js and xml2js to generate an XML sitemap.xml. Everything seems to be in order, but when I try to define attributes like: '$': { 'xmlns': 'http://www.sitemaps.org/schemas/sitemap/0 ...

Sending JSON data containing an IFormFile and a string as parameters to C#

Software Versions: ASP.NET and Web Tools - 17.10.341.11210 C# Tools - 4.10.0-3.24312.19+ JQuery - 3.3.1.js JS - 2.8.3.js Currently, I am attempting to pass an IFormFile and a string from a JSON file select and a string input. After thorough testing, I ha ...

What could be the reason behind the malfunction of this jQuery post request?

I am currently studying AJAX with jQuery, but I am facing an issue with my registration system. The following code does not seem to work: $('#submitr').click(function () { var username = $('#usernamefieldr').val(); var password ...

How to delete the final character from a file stream using node.js and the fs module

My current project involves using node.js to create an array of objects and save them to a file, utilizing the fs library. Initially, I set up the write stream with var file = fs.createWriteStream('arrayOfObjects.json'); and wrote an opening brac ...

JavaScript-generated buttons fail to trigger VueJS functions

I have a function that creates buttons for each item in a list, and each button is supposed to execute a function in the App.vue file when clicked. The issue I am facing is that neither the onclick nor the v-on:click methods are functioning as expected. ...

How do I search for a JSON object in JavaScript?

I have an array containing screen resolutions and I need to find the correct resolution range for the user's viewport (I have the width x height of the current window). Here is the sample JavaScript array with JSON objects: [ {width:100,height:200, ...

The issue with React select right-to-left (RTL) functionality is that it

When using react select, I include isRtl as a prop like so: <Select onChange={handleChange} isRtl isMulti options={colourOptions} /> However, only the input receives the rtl direction style and not the options. How can I ensure that both the input a ...

Using JavaScript with React to invoke an asynchronous action within a component

Within my class, I have implemented some asynchronous actions in the ComponentDidMount method. The code snippet looks like this: componentDidMount(){ // var my_call = new APICall() Promise.resolve(new APICall()).then(console.log(FB)) } class API ...

Choosing a service endpoint based on URL patterns with Express-Gateway

I am faced with the challenge of consolidating multiple individual servers under the same domain behind a gateway. Currently, each server has different accessible names from the outside world. Our sales team wishes to offer customers unique URLs, leading t ...

Using a computed property setter in Vue.js/Javascript while focusing on a datepicker can lead to crashing the browser

Can anyone explain why my javascript / vuejs code is crashing on my JSFiddle when I focus on the start date datepicker (causing the browser to hang)? If you uncomment the endDate computed property and comment out the current one, it works fine but the fun ...

Javascript experiencing issues with Heapsort

I have been working on implementing heapsort in JavaScript, but I've encountered an issue with an undefined element at position array.length - 2, and the element at index 0 is not sorted. Here is the code snippet: var heapSort = function(array) { ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...