Javascript 如何返回添加了练习字段的用户对象?
我正在FreeCodeCamp上做这个练习跟踪RESTAPI项目。我的代码似乎给出了正确的输出,但没有通过测试可以通过将表单数据userId(_id)、描述、持续时间和可选日期发布到/api/exercise/add来向任何用户添加练习。如果未提供日期,则将使用当前日期。应用程序将返回添加了练习字段的用户对象。 我为这个特殊测试编写的代码Javascript 如何返回添加了练习字段的用户对象?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我正在FreeCodeCamp上做这个练习跟踪RESTAPI项目。我的代码似乎给出了正确的输出,但没有通过测试可以通过将表单数据userId(_id)、描述、持续时间和可选日期发布到/api/exercise/add来向任何用户添加练习。如果未提供日期,则将使用当前日期。应用程序将返回添加了练习字段的用户对象。 我为这个特殊测试编写的代码 app.post("/api/exercise/add", urlencodedParser, async (req, res) =>
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" });
}
});
同样为了方便起见,我编写了这样的模式
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);
对于这段代码,我得到了输出
{"username":"Tanjim","id":"5f1939c3466036054f22511f","exercise":[{"description":"pushups","duration":"21","date":"2019-09-13"}]}
但仍然无法通过测试。有人能帮我解决这个问题吗?你有没有试过在freecodecamp论坛上提问?这些测试是为了寻找特定的条件。您的代码可能是正确的,但仍然无法通过测试。检查@nibble我同时也问了。让我们看看我是否得到任何反馈,在我的第一条评论中检查链接。很可能有人已经遇到了相同的问题。@nibble yes检查它。有时令人沮丧的是,您花了数小时编写它,给出了正确的输出,但由于某些原因,它没有通过测试