I am doing this exercise tracker REST api project on FreeCodeCamp. My code seems to give the correct output but it is failing to pass the test can add an exercise to any user by posting form data userId(_id), description, duration, and optionally date to /api/exercise/add. If no date supplied it will use current date. App will return the user object with the exercise fields added. My code for this particular test
app.post("/api/exercise/add", urlencodedParser, async (req, res) => {
const params = req.body;
try {
if (
params.description === "" ||
params.duration === "" ||
params.userId === ""
) {
return res.json({ error: "please enter required fields" });
}
if (params.date === "" || params.date === null) {
params.date = new Date().toISOString().substring(0,10);
}
var existingUser = await Username.findById({ _id: params.userId });
if (existingUser._id === null) {
return res.json({
error: "could not find the ID. enter the correct one"
});
} else if (String(existingUser._id) === params.userId) {
var assignExercise = Object.create(Exercise);
assignExercise.description = params.description;
assignExercise.duration = params.duration;
assignExercise.date = params.date;
existingUser.exercise.push({
description: assignExercise.description,
duration: assignExercise.duration,
date: assignExercise.date
});
existingUser.count = existingUser.exercise.length;
await existingUser.save();
res.json({
username:existingUser.username,
id:existingUser._id,
exercise:existingUser.exercise
});
}
} catch (err) {
console.log(err);
res.json({ error: "A problem occured. Solve it" });
}
});
also for the convenience, I wrote the schema like this
const Exercise = {
description: String,
duration: Number,
date: { type: Date, default: Date.now }
};
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
count: {
type: Number
},
exercise: {
type: Array,
value: Exercise
}
});
const Username = mongoose.model("Username", userSchema);
for this code I get the output
{"username":"Tanjim","id":"5f1939c3466036054f22511f","exercise":[{"description":"pushups","duration":"21","date":"2019-09-13"}]}
But still can't pass the test. Can anyone help me regarding this?