简体   繁体   中英

Adding JSON array to a Mongoose schema (JavaScript)

I'm creating an Android App (A baseball app) where I'm using MongoDB to store my data. the way I want my JSON data to be stored into the database is like this.

{"email@domain.com":{
      "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"}
      ]  
}

sorry if there is any syntax error, but essentially that is the layout i want for the JSON. Where the mongo page "id" is the persons email. and where "players" is an array of the list of players the coach has. My question is, how can I

  1. properly setup the Mongoose schema to look like this?

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

  3. and if possible (ill try and figure this part on my own if no one can) if multiple players are being added at once, how can i store them if there's already players in the array?

All of this is backend/server side, I have the android working properly, i just need help with storing it to look like this in JavaScript.

  1. You dont want to use a dynamic variable as a field name. I'm talking about the email you have "email@domain.com". This wouldn't be good because how will you find the object. Its not common to search for object by there fields, you use the field name to describe what it is your looking for. You will need 2 models. One for player and one for coach. Coach refrences a Player in its Players array field.
  2. If you format your JSON correctly you wont have to do any parsing, just make sure the JSON you are sending is correctly formatted.
  3. 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({
                // Put 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({
                // Put 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM