FCC Exercise Tracker adding exercises

Viewed 1179

I am stuck on Test #3 and at a loss. Any help, advice or suggestions are welcome. I am using Glitch to write my code. Everything syncs up to my database which is MongoDB. Just can't pass that test and I would suspect you would need to in order to get 4, 5, and 6 done. I am new to coding, so be nice lol Thank you

https://github.com/rbill314/Exercise-Tracker-.git

const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const moment = require("moment");
const shortId = require("shortid");

/*Connect to database*/
mongoose.connect(process.env.URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

if (mongoose.connection.readyState) {
  console.log("Holy Crap! It Connected");
} else if (!mongoose.connection.readyState) {
  console.log("WHACHA DO!!!");
}

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");
});

/*Model*/
const userSchema = new mongoose.Schema({
  _id: { type: String, required: true, default: shortId.generate },
  username: { type: String, required: true },
  count: { type: Number, default: 0 },
  log: [
    {
      description: { type: String },
      duration: { type: Number },
      date: { type: Date }
    }
  ]
});

const User = mongoose.model("User", userSchema);

/*Test 1: You can POST to /api/users with form data username to create a new user.
    The returned response will be an object with username and _id properties.*/

app.post("/api/users", (req, res) => {
  User.findOne({ username: req.body.username }, (err, foundUser) => {
    if (err) return;
    if (foundUser) {
      res.send("Username Taken");
    } else {
      const newUser = new User({
        username: req.body.username
      });
      newUser.save();
      res.json({
        username: req.body.username,
        _id: newUser._id
      });
    }
  });
});

/*Test 2: You can make a GET request to /api/users to get an array of all users.
    Each element in the array is an object containing a user's username and _id.*/

app.get("/api/users", (req, res) => {
  User.find({}, (err, users) => {
    if (err) return;
    res.json(users);
  });
});

/*Test 3: You can POST to /api/users/:_id/exercises with form data description, duration, and optionally date.
    If no date is supplied, the current date will be used.
        The response returned will be the user object with the exercise fields added.*/

app.post("/api/users/:_id/exercises", (req, res) => {
  const { _id, description, duration, date } = req.body || req.params;
  User.findOne({ _id }, (err, userFound) => {
    if (err)
      return res.json({
        error: "Counld not find Carmen Sandiego"
      });

    let exerDate = new Date();
    if (req.body.date && req.body.date !== "") {
      exerDate = new Date(req.body.date);
    }

    const exercise = {
      description: description,
      duration: duration,
      date: exerDate
    };
    userFound.log.push(exercise);
    userFound.count = userFound.log.length;
    userFound.save((err, data) => {
      if (err)
        return res.json({
          error: "Not letting you save today"
        });
      const lenOfLog = data.log.length;

      let displayDate = moment(exercise.date)
        .toDate()
        .toDateString();

      let sendData = {
        username: data.username,
        description: data.log[lenOfLog - 1].description,
        duration: data.log[lenOfLog - 1].duration,
        _id: data._id,
        date: displayDate
      };

      res.send(sendData);
    });
  });
});

/*Test 4: You can make a GET request to /api/users/:_id/logs to retrieve a full exercise log of any user.
    The returned response will be the user object with a log array of all the exercises added.
        Each log item has the description, duration, and date properties.*/

/*Test 5: A request to a user's log (/api/users/:_id/logs) returns an object with a count
    property representing the number of exercises returned.*/

/*Test 6: You can add from, to and limit parameters to a /api/users/:_id/logs request to retrieve part
    of the log of any user. from and to are dates in yyyy-mm-dd format. limit is an integer of how many 
      logs to send back.*/

/*listener*/
const listener = app.listen(process.env.PORT || 3000, () => {
  console.log("Shhhhh!!!! Spying on port " + listener.address().port);
});
1 Answers
//Excercise Schema
const exSchema=new Schema({
  description:{
    type:String,
    required:true
  },
  duration:{
    type:Number,
    required:true
  },
  date:String
})
//User Schema
const userSchema=new Schema({
  username:{
    type:String,
    required:true
  },
  log:[exSchema]
})
const User=mongoose.model("User",userSchema)
const ExModel=mongoose.model("Excercise",exSchema)

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


//Endpoind Of user
app.route("/api/users").post(async(req,res)=>{
  const{username}=req.body
  const user=await User.create({username:username})
  res.json(user)
}).get(async(req,res)=>{

const user=await User.find()

res.json(user)
})

//Excercise Endpoint

app.post("/api/users/:_id/exercises",async(req,res)=>{
  const{description,duration,date}=req.body
  const{_id}=req.params
  let excercise=await ExModel.create({description,duration:parseInt(duration),date})
  if(excercise.date===""){
    excercise.date=new Date(Date.now()).toISOString().substr(0,10)
  }
  await User.findByIdAndUpdate(_id,{$push:{log:excercise} },{new:true},(err,user)=>{
    let responseObj={}
    responseObj["_id"]=user._id
    responseObj["username"]=user.username
    responseObj["date"]=new Date(excercise.date).toDateString(),
    responseObj["description"]=excercise.description,
    responseObj["duration"]=excercise.duration

    res.json(responseObj)
  })

  res.json({})

})

//Logs Endpoint
app.get("/api/users/:_id/logs",async(req,res)=>{
  if(req.params._id){
    await User.findById(req.params._id,(err,result)=>{
    if(!err){
      let responseObj={}
      responseObj["_id"]=result._id
      responseObj["username"]=result.username
      responseObj["count"]=result.log.length
      
      if(req.query.limit){
        responseObj["log"]=result.log.slice(0,req.query.limit)
      }else{
        responseObj["log"]=result.log.map(log=>({
        description:log.description,
        duration:log.duration,
        date:new Date(log.date).toDateString()
      }))
      }
      if(req.query.from||req.query.to){
        let fromDate=new Date(0)
        let toDate=new Date()
        if(req.query.from){
          fromDate=new Date(req.query.from)
        }
        if(req.query.to){
          toDate=new Date(req.query.to)
        }
        fromDate=fromDate.getTime()
        toDate=toDate.getTime()
        responseObj["log"]=result.log.filter((session)=>{
          let sessionDate=new Date(session.date).getTime()

          return sessionDate>=fromDate&&sessionDate<=toDate
        })
      }
      res.json(responseObj)
    }else{
      res.json({err:err})
    }
  })
  }else{
    res.json({user:"user not found with this id"})
  }
})
Related