Story 8th:The response returned from POST /api/users/:_id/exercises
will be the user object with the exercise fields added.
Hi, I’m stuck and fail this story for hours and not be able to find the error.
My out put response works find as example:
{"username":"daro","_id":"6167d3edd01e8cbd902a2a05","date":"Thu Oct 14 2021","duration":234,"description":"running"}
my server code is:
const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
const bodyParser = require('body-parser');
const ObjectId= require('mongodb').ObjectId;
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);
const User = mongoose.model('User', new mongoose.Schema({
username: {type: String, required: true},
log: Array
}));
const Exercises = mongoose.model('Exercises', new mongoose.Schema({
description: {type:String, required: true},
duration: {type:Number, required: true},
date: String
}));
app.use(cors())
app.use(express.static('public'))
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
app.post('/api/users', (req,res)=>{
let newUser = new User({
username: req.body.username,
log: []
});
newUser.save((err,data)=>{
if (err) return console.log(err);
res.json({
username: data.username,
_id: data.id
});
});
});
app.get('/api/users',(req,res)=>{
let array=[];
User.find({},function(err,allUserArray){
if (err) return console.log(err);
let returnArray = allUserArray.map(user=>{
return {username:user.username,_id:user.id};
})
res.json(returnArray);
});
});
function convertDate(date){
if (date){
return new Date(date).toDateString();
} else {
return new Date().toDateString();
}
}
app.post('/api/users/:_id/exercises',(req,res)=>{
User.findById(req.body[':_id'],(err,result)=>{
if (err) return console.log(err);
if (result==null){
res.send("_id Not Found");
} else {
new Exercises({
description: req.body.description,
duration: parseInt(req.body.duration),
date: convertDate(req.body.date)
}).save((err,data)=>{
if (err) return console.log(err);
result.log.push(data);
result.save((err,savedresult)=>{
if (err) return console.log(err);
});
res.json({
username: result.username,
_id: result.id,
date: data.date,
duration: data.duration,
description: data.description
});
});
}
});
});
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
Where I deploy: https://quiet-peak-63138.herokuapp.com/
Does anyone know what’s wrong and how to fix it?