I’m in the Exercise Tracker Back End Challenge, and I’m having trouble passing these two tests:
Test 7: " 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."
Test 8: " The response returned from POST /api/users/:_id/exercises
will be the user object with the exercise fields added." together.
I have the following code:
const userSchema = new Schema({
username: {type: String, required: true},
count: {type: Number, default: 0},
log: [{
description: {type: String, required: true},
duration: {type: Number, required: true},
date: String
}]
});
and
app.post('/api/users/:_id/exercises', function(req, res) {
const id = req.body[':_id'];
const description = req.body.description;
const duration = Number(req.body.duration);
const date = req.body.date == '' ? new Date().toDateString() : new Date(req.body.date).toDateString();
let newExercise = {
description: description,
duration: duration,
date: date
};
// ... Then tried 2 alternatives:
// Method 1 for updating :
User.updateOne({_id: id}, {$push: {log: newExercise}, $inc: {count: 1}}, function(err, user) {
if (err) return console.error(err);
res.send({username: ???, description: description, duration: duration, date: date, _id: id});
});
// Method 2 for updating:
User.findByIdAndUpdate({_id: id}, {$push: {log: newExercise}, $inc: {count: 1}}, {new: true}, function(err, user) {
if (err) return console.error(err);
res.send({username: user.username, description: description, duration: duration, date: date, _id: id});
});
});
If I use Method 1 for updating, Test 7 passes but I can’t access the username so I can’t get Test 8 to pass. And if I use method 2, apparently I can get the required response but neither Test 7 or 8 pass. I tried it also with findByIdAndUpdate.
I think there’s something I’m not understanding about the latter methods, because if updateOne works for Test 7 it seems to me logical that findOneAndUpdate should work too.
Edit:
This is the link to the boilerplate: https://boilerplate-project-exercisetracker.juanrozo89.repl.co
Thanks in advance