I have my code below, and it has the outputs exactly the same like the example of FCC provided… But, unfortunately, the only the first test that is passed. are anyone having solution about this?
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const { Schema } = require('mongoose')
require('dotenv').config()
app.use(express.urlencoded({ extended: true }))
// MongoDB Database
// mongoose.connect()
const Exercise = mongoose.model('Exercise', {
username: {
type: String,
required: true
},
log: [{
description: String,
duration: Number,
date: String,
_id: false
}]
})
app.get('/api/users', async (req, res) => {
const users = await Exercise.find({}, ['username', '__v'])
res.json(users)
})
app.get('/api/users/:_id/logs', async (req, res) => {
let { from, to, limit } = req.query
limit = limit == undefined ? 1000 : limit
from = new Date(from) == 'Invalid Date' ? new Date(0) : new Date(from)
to = new Date(to) == 'Invalid Date' ? new Date() : new Date(to)
const user = await Exercise.findById(req.params._id)
if (user == null) return res.json({ error: 'Cannot find the user' })
const result = { ...user._doc }
delete result.__v
const filtered = result.log.filter((element, index) => (index < limit) && (new Date(element.date) > from) && (new Date(element.date) <= to))
result.log = filtered
res.json({
_id: result._id,
username: result.username,
count: result.log.length,
log: result.log
})
})
app.post('/api/users', async (req, res) => {
const username = await req.body.username
const test = await Exercise.findOne({ username })
if (test != null) { console.log('Name already taken') }
else {
// Create User
const user = { username: username }
const wait = await Exercise.insertMany(user)
console.log('saved')
}
const result = await Exercise.findOne({ username: username })
res.json({
username: result.username,
_id: result._id
})
})
app.post('/api/users/:_id/exercises', async (req, res) => {
const id = req.params._id
const user = await Exercise.findById(id)
let d = new Date(req.body.date) == 'Invalid Date' ? new Date() : new Date(req.body.date)
d = d.toDateString()
const input = {
description: req.body.description,
duration: Number(req.body.duration),
date: d
}
user.log.push(input)
const wait = await Exercise.findByIdAndUpdate(id, user)
res.json({
username: user.username,
description: req.body.description,
duration: parseInt(req.body.duration),
date: d,
_id: user._id
})
})
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
here’s the challenge link
Back End Development and APIs Projects - Exercise Tracker | Learn | freeCodeCamp.org