Как разместить массив объектов JSON на mongodb? - PullRequest
0 голосов
/ 07 апреля 2020

Я пытаюсь создать приложение для управления тренировками, которое позволяет тренеру (userType = true) создать тренировку для пользователя. К сожалению, я не уверен, как отформатировать мою схему mongodb, чтобы получить количество упражнений. Моя идея состояла в том, чтобы создать массив JSON объектов, которые я затем поместил бы sh в базу данных для последующего отображения пользователю. Проблема в том, что я не знаю, как правильно создать форму, которая позволила бы правильно анализировать данные. Я решил создать несколько форм и затем преобразовать их в JSON объекты, используя метод .serializeObject () в JQuery, а затем поместить их * * в массив. Однако я не знаю, как создать sh этот массив на mongoDB

Вот мой файл gym.hbs

<div id ="createWorkout" class="hiddenWorkout workoutCreator">
      <form id="exerciseForm" class="gymFormPadding" action="/dashboard/gym" method="POST">
    <div id="exerciseInput" class="form-group" style="display:flex;width:100%">
        <input id="exerciseName" class="form-control" type="text" name="name" placeholder="Exercise Name" value=""/>        
        <input id="exerciseSets" class="form-control" type="number" name="sets" placeholder="Sets" value=""/>        
        <input id="exerciseReps" class="form-control" type="number" name="reps" placeholder="Reps" value=""/>        
        <input id="exerciseWeight" class="form-control" type="number" name="weight" placeholder="Weight" value="" /> 

      </div>
      </form>
      <div id="newExerciseAdd"></div>

    <input type="hidden" name="_csrf" value="{{cybersecurity}}">           
    <button type="button" class="btn btn-primary" id="addExerciseAdd">Add New Exercise</button>               
    <button id="submitWorkout" type="submit"  class="btn btn-primary"  name="upload">Submit Workout</button>     

    </div>

Это JQuery, ответственный за операции

  var counter = 1;
  $(document).ready(function(){
        $("#createWorkout").click(function(){
            $(".hiddenWorkout").removeClass('hiddenWorkout'); 
            $("#createWorkout").hide();
        });
    });

    $(document).ready(function(){
      var i = 0;
        $("#addExerciseAdd").click(function(){
          if(i<9){
            $("#exerciseForm").clone().appendTo("#newExerciseAdd");
            i++;
            $("#newExerciseAdd #exerciseForm").attr("id","exerciseForm"+i);
            $("#newExerciseAdd #exerciseInput").attr("id","exerciseInput"+i);
            $("#newExerciseAdd #exerciseName").attr("id","exerciseName"+i);
            $("#newExerciseAdd #exerciseSets").attr("id","exerciseSets"+i);
            $("#newExerciseAdd #exerciseReps").attr("id","exerciseReps"+i);
            $("#newExerciseAdd #exerciseWeight").attr("id","exerciseWeight"+i);
            counter++;
            }

        });

    });


   $(document).ready(function(){
      var array = [];
      var object;
      var exerciseNo = exerciseNo;
        $("#submitWorkout").click(function(){
          $("#exerciseForm").attr("id","exerciseForm0");
          $("#exerciseInput").attr("id","exerciseInput0");
          $("#exerciseName").attr("id","exerciseName0");
          $("#exerciseSets").attr("id","exerciseSets0");
          $("#exerciseReps").attr("id","exerciseReps0");
          $("#exerciseWeight").attr("id","exerciseWeight0");
          for(var i=0;i<counter;i++){
          object=$("#exerciseForm"+i).serializeObject();
          array.push(object);
          }
        });
        console.log(array);
    }); 

это мой контроллер. js

const mongoose = require('mongoose');
const Gym = require('../models/gym');




exports.getGymPage = async (req, res) =>
{
    let coachStatus = req.user.userType;
    let teamID = null;
    if(res.locals.team){teamID = res.locals.team._id}   
    let exercises = await Gym.find({teamId:teamId});
    res.render('/dashboard/gym.hbs',{title: "Gym",exercises : exercises, coachStatus : coachStatus, cybersecurity: `${req.csrfToken()}`});
};

exports.addExercise = (req, res) =>
{
    const exercise = new Gym({teamID:res.locals.team._id, name: req.body.exerciseName,sets:req.body.exerciseSets,reps:req.body.exerciseReps,weight:req.body.exerciseWeight,cybersecurity: `${req.csrfToken()}`}).save();
    res.redirect('/dashboard/gym');
}

и это мои модели. js

const mongoose = require('mongoose');
const { Schema } = mongoose;

const gymSchema = new Schema({
    teamID : {
        type: mongoose.Schema.ObjectId
    },

exercises:[{
    name :{ type:String, require: true},
    sets : [],
    reps : { type: Number, require: true},
    weight : { type: Number,},

}]
});

module.exports = mongoose.model('Gym', gymSchema);

- это мой метод полного выталкивания файлов абсурдным? Я чувствую, что вращаюсь в кругах и ничего не получаю с этим. Есть ли намного лучший способ сделать это?
Пожалуйста, извините за мой наиболее вероятный ужасный код, я только начинаю. Спасибо!

1 Ответ

0 голосов
/ 07 апреля 2020

MongoDB должен знать, что это массив данных. Вы пытались получить доступ к упражнению, выполнив это, например, для ...:

const exercise = req.body.exercise[0].name;
const exerciseData = JSON.parse(exercise);

А затем для pu sh, вы можете просто использовать обычный массив однако надеяться, что это поможет ...

...