Я действительно искал в Интернете эту проблему, но не могу найти решение. Я пробую разные виды заселения и ничего не получается. Некоторые темы говорили об антипаттерне, но я не думаю, что это мой случай. Вот проблема:
У меня есть модель Session, содержащая поддокумент ProgramExercise:
const mongoose = require('mongoose');
const sessionExerciseSchema = new mongoose.Schema({
exercise: {
type: mongoose.Schema.Types.ObjectId, ref: 'Exercise', // REFERENCE TO OTHER MODEL
required: true
},
type: {
type: String,
enum: ['Reps', 'Duration'],
required: true
},
// If type is Repetitions
repsProgram: [{
type: Number,
required: function() {
return (this.exerciseType === 'Repetitions');
}
}],
repsDone: [{
type: Number
}],
// If type is Duration
durationProgram: [{
type: Number,
required: function() {
return (this.exerciseType === 'Duration');
}
}],
durationDone: [{
type: Number
}],
restDurationProgram: {
type: Number
},
dateDone: {
type: Date
}
});
const sessionSchema = new mongoose.Schema({
programId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Program',
required: true
},
name: {
type: String,
trim: true,
required: true,
minlength: 1,
maxlength: 200
},
date: {
type: String,
required: true
},
time: {
type: String,
required: true
},
dateDone: {
type: Date
},
exercises:[
sessionExerciseSchema // HERE : SUB DOCUMENT
]
});
module.exports = mongoose.model('Session', sessionSchema);
Как вы можете видеть, моя ProgramExercise, которая является вложенной моделью, ссылается на другую модель с именем Exercise, но на этот раз по ObjectID (поэтому он должен быть заполнен). Это моя модель упражнения:
const mongoose = require('mongoose');
const exerciseSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
minlength: 1,
maxlength: 300,
unique: true
},
description: {
type: String,
trim: true,
required: true,
minlength: 50,
maxlength: 1000
},
imageUrl: {
type: String,
trim: true,
minlength: 1,
maxlength: 400
}
});
module.exports = mongoose.model('Exercise', exerciseSchema);
Теперь моя проблема: когда я пытаюсь получить сессию со всеми ее программными упражнениями и заполненными упражнениями, я не могу заставить его работать. Самое близкое, что я получаю, это когда я делаю так:
router.get('/exercises/:id', /*requiresLogin,*/(req, res) => {
// Get session exercises
Session
.findById(req.params.id)
.populate('exercises.exercise')
.exec()
.then((session) => {
res.header("Access-Control-Allow-Origin", "*");
res.json(session.exercises);
})
.catch(function (e) {
console.error(e);
res.sendStatus(500);
});
});
Проблема в том, что в моем ответе я заполнил только первый элемент Session.exercises.exercise! Но так как упражнения - это массив (из ProgramExercise), мне нужно заполнить упражнение для каждого объекта ProgramExercise!
Надеюсь, мои объяснения не были слишком запутанными. Заранее спасибо!