I’m working on Back End Development and APIs.
But the section of exercise tracker I have failed to pass last two tasks(points) in order to complete.
- The date property of any object in the log array that is returned from
GET /api/users/:id/logs
should be a string… Use the dateString format of theDate
API. - You can add
from
,to
andlimit
parameters to aGET /api/users/:_id/logs
request to retrieve part of the log of any user.from
andto
are dates inyyyy-mm-dd
format.limit
is an integer of how many logs to send back.
I’m waiting for your help in order to win this certificate.
myCodes:
//start
const express=require("express");
const app = express()
const cors = require('cors')
const mongoose = require("mongoose")
const bodyParser = require("body-parser")
require('dotenv').config()
app.use(cors())
app.use(express.static('public'))
app.use(bodyParser.urlencoded({extended:false}))
const uri = "";
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
let schema = new mongoose.Schema({
username: String,
exercices: [
{
description: { type: String },
duration: { type: Number },
date: { type: String, required: false }
}
]
})
let Users = mongoose.model("Users", schema)
const defaultDate = () => new Date().toISOString().slice(0, 10)
app.post("/api/users", (req,res) => {
let user = new Users({
username: req.body.username
})
user.save((err,data) => {
if(err) return console.log(err)
console.log("User saved successfully")
})
res.json(user)
})
app.get("/api/users", (req,res) => {
Users.find({username: /\w/},(err,data) => {
if(err) return console.log(err)
res.json(data)
})
})
app.post("/api/users/:_id/exercises", (req,res) => {
const userId = req.params._id
let exercises = {
description: req.body.description,
duration: Number(req.body.duration),
date: req.body.date || defaultDate()
}
Users.findByIdAndUpdate(
userId, // find user by _id
{$push: { exercices: exercises } }, // add exObj to exercices[]
{new: true},
(err, data) => {
if(err) return console.log(err)
let returnObj = {
username: data.username,
description: exercises.description,
duration: exercises.duration,
_id: userId,
date: new Date(exercises.date).toDateString()
};
res.json(returnObj);
}
);
})
app.get("/api/users/:_id/logs", (req,res) => {
const userId = req.params._id;
Users.findById(userId, (err,data) => {
if(err) return console.log(err)
let user = new Users({
username: data.username,
exercices: [
data.duration,
data.description,
new Date(data.date).toDateString()
]
})
res.json({
user,
count:data.exercices.length,
log:data.exercices
})
})
})
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
//end
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
Challenge: Exercise Tracker
Link to the challenge: