MongoDB / mongoose在两个模型之间创建关系?

时间:2015-08-09 03:43:08

标签: node.js mongodb mongoose

我希望按照此模式http://docs.mongodb.org/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/

创建一对多关系

我有一个Exercise.js架构,其中包含一系列练习。

var exerciseSchema = new mongoose.Schema({

  _id: String,
  title: String,
  description: String,
  video: String,
  sets: Number,
  reps: String, 
  rest: Number

});

然后我有一个锻炼计划BeginnerWorkout.js架构

var workoutDaySchema = new mongoose.Schema({

  _id: String,
  day: Number,
  type: String,
  exercises: Array

});

我想将一系列练习与workoutDaySchema相关联,其中包含一系列特定锻炼的锻炼日,每天都有一系列练习。

我有一个播种功能可以为我生成锻炼。

check: function() {

    // builds exercises
    Exercise.find({}, function(err, exercises) {
        if(exercises.length === 0) {
            console.log('there are no beginner exercises, seeding...');
            var newExercise = new Exercise({
                _id: 'dumbbell_bench_press',
                title: 'Dumbbell Bench Press',
                description: 'null',
                video: 'null',
                sets: 3, // needs to be a part of the workout day!!
                reps: '12,10,8', 
                rest: 1
            });
            newExercise.save(function(err, exercises) {
                console.log('successfully inserted new workout exercises: ' + exercises._id);
            });
        } else {
            console.log('found ' + exercises.length + ' existing beginner workout exercises!');
        }
    });


    // builds a beginner workout plan
    BeginnerWorkout.find({}, function(err, days) {
        if(days.length === 0) {
            console.log('there are no beginner workous, seeding...');
            var newDay = new BeginnerWorkout({
                day: 1,
                type: 'Full Body',
                exercises: ['dumbbell_bench_press'] // here I want to pass a collection of exercises.
            });
            newDay.save(function(err, day) {
                console.log('successfully inserted new workout day: ' + day._id);
            });
        } else {
            console.log('found ' + days.length + ' existing beginner workout days!');
        }
    });

}

所以我的问题是建立一个锻炼计划,如何使用猫鼬将练习关联到exercises密钥?

1 个答案:

答案 0 :(得分:1)

试试这个:

exercises: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Exercise', required: false }]

使用exercise._id为锻炼添加锻炼(在上面的代码中,您需要将其放入相关的回调中,例如练习中.save的回调):

newDay.exercises.push(newExercise._id);

_id通常是生成的数字,因此我不知道您是否可以将其设置为您建议的文本字符串。

当你.find()锻炼时,你也需要填充练习。类似的东西:

BeginnerWorkout.find({}).
    .populate('exercises')
    .exec(function(err, exercises) {
    //etc