英文:
MongoDB: How to create an object that has an array of objects as a field?
问题
const SingleExerciseSchema = new Schema({
exerciseName: { type: String },
setLog: [{
weight: { type: Number },
sets: { type: Number },
reps: { type: Number },
}],
});
const DATA = [
{ exerciseName: "Squat",
setLog: [
{weight: 65, sets: 1, reps: 5},
{weight: 55, sets: 2, reps: 5},
{weight: 45, sets: 1, reps: 5},
]
},
{ exerciseName: "Overhead Press",
setLog: [
{weight: 27.5, sets: 1, reps: 5}
]
}
];
const exerciseObjectList = (req.body).map(
(exerciseLog) => new SingleExercise({
exerciseName: exerciseLog.exerciseName,
setLog: exerciseLog.setLog,
}));
英文:
I have this schema:
const SingleExerciseSchema = new Schema({
exerciseName: { type: String },
setLog: [{
weight: { type: Number },
sets: { type: Number },
reps: { type: Number },
}],
});
Then I get data like this, as a json:
const DATA = [
{ exerciseName: "Squat",
setLog: [
{weight: 65, sets: 1, reps: 5},
{weight: 55, sets: 2, reps: 5},
{weight: 45, sets: 1, reps: 5},
]
},
{ exerciseName: "Overhead Press",
setLog: [
{weight: 27.5, sets: 1, reps: 5}
]
}
];
I want to loop over the data and create my SingleExercise objects from it.
Like this:
const exerciseObjectList = (req.body).map(
(exerciseLog) => new SingleExercise({
exerciseName: req.body.exerciseName,
setLog: // stuck here
})
However, I'm not sure to update/access the setLog fields, syntax wise. I want something like this:
const exerciseObjectList = (req.body).map(
(exerciseLog) => new SingleExercise({
exerciseName: req.body.exerciseName,
setLog: {
(req.body.setLog).map(
(set) => {
weight: set.weight,
sets: set.sets,
reps: set.reps,
}
)
}
})
);
but it's obviously wrong syntax.
Edit: I actually had a stupid mistake in my code, I wrote req.body.exerciseName instead of exerciseLog.exerciseName in my loop.
Also, I just went with
setLog: exerciseLog.setLog
and it works (instead of accessing each field inside setLog separately).
I still don't know how to access each field separately, but for now, I don't need to do that.
Fixed code:
const exerciseObjectList = (req.body).map(
(exerciseLog) => new SingleExercise({
exerciseName: exerciseLog.exerciseName,
setLog: exerciseLog.setLog,
}));
答案1
得分: 2
I believe you can just map over the req.body and add the element inside each new SingleExercise
const exerciseObjectList = req.body.map(exercise => new SingleExercise(exercise))
英文:
I believe you can just map over the req.body and add the element inside each new SingleExercise
const exerciseObjectList = req.body.map(exercise => new SingleExercise(exercise))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论