【问题标题】:FCC Exercise Tracker adding exercisesFCC 锻炼追踪器添加锻炼
【发布时间】:2022-02-03 17:36:31
【问题描述】:

我被困在测试#3 并且不知所措。欢迎任何帮助、建议或建议。我正在使用 Glitch 编写我的代码。一切都同步到我的数据库,即 MongoDB。只是无法通过该测试,我怀疑您需要这样做才能完成 4、5 和 6。我是编码新手,所以请多多关照,谢谢

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

【问题讨论】:

  • 问题是我在正文中留下了一个字符串的持续时间...parsInt(duration)...在我的 GitHub 上更新

标签: javascript api mongoose backend


【解决方案1】:
//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"})
  }
})

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 2019-11-10
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2010-11-27
相关资源
最近更新 更多