Saving to an array in MongoDB

Saving to an array in MongoDB
0

#1

Hello I’m having trouble saving the array(exercises) to the record. I get the userId and username but won’t saving anything else in the app.post("/api/exercise/add/"

//Structure of database
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;

 const userSchema = new Schema({
   _id: String,
   user_name: String,
   exercises: [{
    exerc_desc: {type: String},
    exerc_dura: {type: String},
    exerc_date: {type: String}
     }]     
  });

  const ModelClass = mongoose.model('userDB', userSchema);

  module.exports = ModelClass;


const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require("mongoose");
const mongodb = require('mongodb').MongoClient();
const userDB = require("./models/userDB");
const dotenv = require("dotenv").config();
const path = require('path');
const randomstring = require("randomstring");

 mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/userdbs')

 app.use(cors())

 app.use(bodyParser.urlencoded({
 extended: false
  }))
app.use(bodyParser.json())

app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});

app.get("/api/exercise/log/", (req, res) => {

    let userID = req.query.userIdGet
    let from_date = new Date(req.query.fromDate)
    let to_date = new Date(req.query.toDate)

   console.log(userID + to_date + from_date)

userDB.findById(req.query.userIdGet, (err, doc) => {
    if (doc) {
        res.json(doc)
    } else {
        res.json({
            error: "user id not found"
        })
    }
})

})

app.post("/api/exercise/new-user/", (req, res) => {

    let username = req.body.username;
    let idUser = randomstring.generate(6);

   userDB.findOne({"user_name": {$eq: username}}, (err, doc) => {

         if (username === "") {
            res.json({
                error: "Username required"
            })
        } else if (doc) {
            return res.send('User already exists')
        } else {
            let newUser = new userDB({
            user_name: username,
            _id: idUser
        });
        newUser.save((err, doc) => {
            res.json({
                user_name: username,
                _id: idUser
              })
          });
        }
    });
});

app.post("/api/exercise/add/", (req, res) => {

let userID = req.body.userId
let desc = req.body.description
let dura = req.body.duration
let date = req.body.date

userDB.findOne({"_id": {$eq: userID}}, (err, doc) => {
  let userName = doc.user_name
  console.log(userName);
    if (doc) {
        let newExercise = new userDB({
            _id: doc._id,
            user_name: doc.user_name,
            exercise: [{
                exerc_desc: req.body.description,
                exerc_dura: req.body.duration,
                exerc_date: req.body.date
            }]
        })

        newExercise.save((err, doc) => {
          
            res.json({
                _id: userID,
                user_name: userName,
                exercises: [{
                    exerc_desc: desc,
                    exerc_dura: dura,
                    exerc_date: date
                }]
            })

        })

    } else {
        res.json({
            error: "user id not found"
        })
    }

});

});

 //Listen on connection port
 let port = process.env.PORT || 3000;
 app.listen(port, () => {
 console.log("Listening on port: " + port);
});

#2

Try:

const userSchema = new Schema({
_id: String,
user_name: String,
exercises: [{
type: Schema.Types.ObjectId, ref: ‘Exercise’
}]
});

const ExerciseSchema = new Schema({
exerc_desc: String,
exerc_dura: String,
exerc_date: String
});

const Exercise = mongoose.model(‘Exercise’, ExerciseSchema)


#3

I’m trying it, wil let you know.