i have been doing this since weeks but it is failing at last test case
here is my code
const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
var bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.connect('mongodb+srv://test:test@cluster0.clk3nrl.mongodb.net/test?retryWrites=true&w=majority',{useNewUrlParser: true, useUnifiedTopology: true});
var db = mongoose.connection;
app.use(express.urlencoded({extended: true}));
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
//mongoose.set('useFindAndModify', false)
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true},
count: Number,
log: [{
description: String,
duration: Number,
date: {type: String, required: false},
_id: false
}]
});
const User = mongoose.model("User", userSchema);
app.post("/api/users", (req,res)=>{
var user = new User({
username: req.body.username
});
user.save(function(err,data){
if(err) return console.error(err);
res.send({
username: data.username,
_id: data._id
})
})
});
app.get("/api/users", (req,res)=>{
User.find({}, function(err,list){
if(err){
console.log(err)
}
else{
res.send(list)
}
})
});
const dateValidation = (input) =>{
if(input === undefined){
return new Date().toDateString()
}
else {
return new Date(input).toDateString()
}
};
app.post("/api/users/:_id/exercises", (req,res)=>{
let exercise = {
description: req.body.description,
duration: parseInt(req.body.duration),
date: dateValidation(req.body.date)
};
User.findOneAndUpdate ({_id: req.params._id}, exercise, {new: true}, (err,data)=>{
if(err){
res.send({
error: err
})
}
else{
data.log.push(exercise);
console.log("saving exercise")
data.save();
res.send({
username: data.username,
_id: req.params._id,
description: exercise.description,
duration: exercise.duration,
date: exercise.date
})
}})
});
app.get("/api/users/:_id/logs?", (req,res)=>{
User.findById(req.params._id, (err,data)=>{
let dataset = data.log;
if (err) {res.send ({error: err}) }
else{
if(req.query.from){
dataset = data.log.filter((item)=>
new Date(item.date).getTime() >= new Date(req.query.from).getTime() && new Date(item.date).getTime() <= new Date(req.query.to).getTime()
)
}
if(req.query.limit){
dataset =data.log.filter((d,i)=> i < req.query.limit )
}
res.send({
_id: data._id,
username: data.username,
from: new Date(req.query.from).toDateString(),
to: new Date(req.query.to).toDateString(),
count: dataset.length,
log: dataset
})
}
})
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
Challenge: Exercise Tracker
Link to the challenge: