Incorporating an array of JSON into a Mongoose schema in JavaScript

I am currently developing an Android App focused on baseball, and I have decided to use MongoDB to store my data. The format in which I would like my JSON data stored in the database is as follows:

{"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f59098949c99b5919a98994b8fb3939597">[email protected]</a>":{
      "coachName": "Smith",
       players:[
            player1:{
                "throws_":"n\/a",
                "position":"position not set",
                "number":"1",
                "playerNum":"H8E83NxRo6",
                "bats":"n\/a",
                "team_name":"Team",
                "name":"Name"
             },
             player2:{
                "throws_":"n\/a",
                "position":"position not set",
                "number":"1",
                "playerNum":"H8E83NxRo6",
                "bats":"n\/a",
                "team_name":"Team",
                "name":"Name"
             }
      ]  
}

If there are any syntax errors, please forgive me, but that's the structure I aim for in my JSON. In this layout, the person's email serves as the Mongo page ID, and "players" represents an array of players under a specific coach. I have several questions regarding implementing this:

  1. How can I properly configure the Mongoose schema to match this structure?

  2. Once the app sends the JSON data, how can I parse it to effectively store the information?

  3. If multiple players are added simultaneously, how can I add them to the existing array of players?

All these aspects pertain to backend/server-side operations. My android application is functioning well, I just require assistance with storing the data as specified using JavaScript.

Answer №1

  1. Avoid using dynamic variables as field names, especially for important data like email addresses. This can make it difficult to locate specific objects in your database. It is recommended to have separate models for players and coaches. The coach model should reference the player model in its Players array field.
  2. Ensure that your JSON data is properly formatted to avoid the need for parsing.
  3. Take a closer look at the addPlayer function.

Controller file (Answer for questions 2 and 3)

create = function(req, res) {
    var coach = new Coach(req.body);
    coach.user = req.user;

    coach.save(function(err) {
        if (err) {
            return res.status(400).send({
                // Include your error message here
            });
        } else {
            res.json(coach);
        }
    });
};

read = function(req, res) {
    res.json(req.coach);
};

addPlayer = function(req, res) {
    var coach = req.coach;
    console.log('updating coach', req.coach);
    var player = new Player(req.newPlayer);
    coach.players.push(newPlayer);

    coach.save(function(err) {
        if (err) {
            return res.status(400).send({
                // Include your error message here
            });
        } else {
            res.json(coach);
        }
    });
};



Player

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Player Schema
 */
var PlayerSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    throws: {
        type: Number,
    },
    name: {
        type: String,
        default: '',
        trim: true
    },
    position: {
        type: String,
        default: '',
        trim: true
    },
    playerNum: {
        type: String,
        default: '',
        trim: true
    },
    position: {
        type: Number,
        default: 0,
        trim: true
    },
    teamName: {
        type: String,
        default: '',
        trim: true
    }
});

mongoose.model('Player', PlayerSchema);

Coach Schema

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Coach Schema
 */
var CoachSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  email: {
    type: String,
    unique: true,
    lowercase: true,
    trim: true,
    default: ''
  },
  name: {
    type: String,
    default: '',
    trim: true
  },
  players: [{
    type: Schema.ObjectId,
    ref: 'Player'
  }]
});

mongoose.model('Coach', CoachSchema);

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

Enhancing Graphics with Anti Aliasing in Three.js and WebGL

While spinning my model with an orbiter, I am experiencing some issues with anti-aliasing. Currently, I am using the following renderer: renderer = new THREE.WebGLRenderer({ preserveDrawingBuffer: true, antialias: true }) ...

Updating an existing value with a cascading dropdown list

My JavaScript code dynamically populates a dropdown list called District based on the selection made by the user in another dropdown list called Department. Here is the snippet of the code: Firstly, I populate the Department dropdownlist and add a ' ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

What is the best way to navigate to the top of a form panel?

I'm currently developing a Sencha Touch mobile app. I have a form panel with multiple fields, so I made it scrollable. However, every time I open the screen (panel), scroll down, navigate to other screens, and then return to the form panel, it stays s ...

What are the common causes of server response issues in AJAX?

I have created a Facebook app that utilizes ajax requests and responses every 3 seconds. The app also has menu items that load content in the main div. All ajax requests are directed to a common.php file. However, some ajax requests are slower than others. ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

Implementing Angular CDK for a dynamic drag-and-drop list featuring both parent and child elements

I'm currently working on setting up a drag and drop list within Angular using the Angular CDK library. My goal is to create a list that includes both parent and child elements, with the ability to drag and drop both parent items as well as their respe ...

What is the best way to manage a multi-select dropdown with checkboxes in Selenium Webdriver?

Below is a snapshot of the drop-down I am working with. In order to handle multiple selections, I currently have code that clicks on the arrow in the drop-down and then selects the corresponding checkbox. However, I would like a more efficient solution fo ...

Do JSON parsers need both a comma and a colon?

The JSON mentioned below has been confirmed to be valid JSON. I have just completed developing a JSON parser that only supports two basic data types: String and Object. Let me demonstrate how the parser functions when there is any ambiguity. parse("{ "Mo ...

typescript warns that an object may be potentially null

interface IRoleAddProps { roles: Array<IRole> } interface IRoleAddState { current: IRole | null } class RoleAdd extends React.Component<IRoleAddProps, IRoleAddState> { state = { current: null, } renderNoneSelect = () ...

I'm trying to access my navigation bar, but for some reason, it's not allowing me to do so

Having trouble getting the navigation bar to open. I have set it up so that when clicked, it should remove the hide-links tag, but for some reason, it does not toggle properly and keeps the ul hidden. import React from "react"; import { NavLink } ...

Angular allows for the creation of dynamic and interactive scenes using Canvas and Three.js

I am in the process of developing a collection of web apps within an Angular SPA. Each individual application is encapsulated within an Angular template, and when navigating between them, specific DOM elements are replaced and scripts from controllers are ...

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

Unable to display Three.JS OBJ Model

I am facing an issue with loading a .obj model in Three.js. I created the model in Cinema 4D, exported it with a scale of 1 meter, and tried to load it using OBJLoader in Three.js. However, even though there are no errors, the model is not showing up. Wh ...

Open the window by using the `Window.open` method, then find and

Is there a way to open a document, not in a new window but on the same page using JavaScript.Window.Open()? Could it be possible to display the document within a specific div element that is obtained with getElementById? For example: document.getElementB ...

Having trouble verifying a user's password in Postman using "bcrypt.compareSync" with Angular and the MEAN stack

I'm currently working on implementing user authentication before adding a JWT token, and I've encountered an issue where the 'if' check is generating this error: node_modules\bcryptjs\dist\bcrypt.js:265 th ...

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

What exactly does the term "library" refer to in the context of jQuery, a JavaScript

I'm confused about the concept of a library - when it comes to jQuery, can it be described as a large file containing multiple plugins that are pre-made and ready for use? ...

Empty req.params in nested ExpressJS routers

I have a unique routing system that relies on the directory structure of my 'api' folder to automatically configure routes. However, I encountered an issue where the req.params object is undefined in the controller when using a folder name as a r ...

Regular expression: match all content up to a certain word(s)

I have two different versions of a string that look like this: The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115 Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 978128011 ...