Add Object Array Subdocument Reactjs and Mongodb

Asked

Viewed 103 times

2

Sirs,

Kindly help me with this doubt?

Summary: I’m creating a mini app using Node/Mongo/React. This app uses relationship in Mongo and would like help to add data via frontend(reactjs) to the array in Mongo.

In the backend works perfectly, I’m not able to assemble, see the code.

Code

Model: CUSTOMER

    const mongoose = require('mongoose')
const Schema = mongoose.Schema

const ClientSchema = new Schema({
    name: {
        type: String
    },

    trainings: [{
        type: mongoose.SchemaTypes.ObjectId,
        ref: 'Training'
    }]
},
    {
        timestamps: true
    })
const Client = mongoose.model('Client', ClientSchema)
module.exports = Client

MODEL : TRAINING

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const TrainingSchema = new Schema(
  {
    user: {
      type: mongoose.SchemaTypes.ObjectId,
      ref: "Client",
      require: true
    },
    nameTrainer: {
      type: String
    },
  },
  {
    timestamps: true
  }
);
const Training = mongoose.model("Training", TrainingSchema);
module.exports = Training;

Would like to insert/add various trainings (which is in the client model) in REACT.

My code in REACT.

import React, { Component } from "react";
import axios from "axios";

export default class Trainer extends Component {
  constructor(props) {
    super(props);

    this.handleChangeNameTrainer = this.handleChangeNameTrainer.bind(this);

    this.handleOnSubmitTrainer = this.handleOnSubmitTrainer.bind(this);

    this.state = {
      clients: []
    };
  }


  handleChangeNameTrainer(e) {
    this.setState({
      nameTrainer: e.target.value
    });
  }

  handleOnSubmitTrainer(e) {
    e.preventDefault();

    const objtrainer = [
      {
        nameTrainer: this.state.nameTrainer,
        nameExercicie: this.state.nameExercicie,

      }
    ];
    axios
      .post(
        "http://localhost:4000/u/add/" + this.props.match.params.id,
        objtrainer
      )
      .then(res => console.log(res.data))
      .catch(error => console.log(error.res));
  }
  render() {
    return (
      <div style={{ maginTop: 10 }}>
        <br />
        <h3>
          Novo Treino de: {this.state.name} {this.state.last_name}
        </h3>
        <br />
        <form onSubmit={this.handleOnSubmit}>
          <div className="form-row">
            <div className="form-group col-md-8 center">
              <label>Nome do Treino:</label>
              <div className="input-group">
                <div className="input-group-prepend">
                  <div className="input-group-text bg-transparent">
                    <i className="far fa-user" />
                  </div>
                </div>
                <input
                  type="text"
                  className="form-control border-left-0 border"
                  value={this.state.nameTrainer}
                  onChange={this.handleChangeNameTrainer}
                  required
                />
              </div>
            </div>
          </div>
          <div className="form-group">
            <button type="submit" className="btn btn-success">
              Adicionar
            </button>
          </div>
        </form>
      </div>
    );
  }
}

To summarize ... I’d like some help from you ...

Below, follows return that would like in React ... Add a new workout ...

{
    "_id": {
        "$oid": "5c8fb4ce37a289357c6c4753"
    },
    "trainings": [
       {
          nameTrainer: "Ombro"
 }
 ],
    "name": "Alice",
}

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.