猫鼬-跨子文档填充导致仅填充数组的第一个元素

时间:2019-10-31 15:32:05

标签: mongoose

我以前确实在网上搜索过此问题,但找不到解决方案。我尝试了不同类型的填充,但没有任何效果。一些主题正在谈论反模式,但是我不认为这是我的情况。问题出在这里:

我有一个包含子文档ProgramExercise的Session模型:

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对象上填充练习!

我希望我的解释不要太混乱。预先感谢!

0 个答案:

没有答案