MongoDB / mongoose在两个模型之间build立关系?

我正在寻找创build一个一对多的关系遵循这种模式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相关联,这包含特定锻炼的训练日的集合,每天都有一系列练习。

我有一个播种function,为我生成锻炼。

 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!'); } }); } 

所以我的问题是在制定一个锻炼计划,我怎样才能把练习关联到使用mongoose的exercises键?

尝试这个:

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

使用exercise._id(在上面的代码中,你需要把它放在相关的callback函数中,例如练习中的.save的callback):

 newDay.exercises.push(newExercise._id); 

_id通常是一个生成的数字,所以我不知道你是否可以将其设置为你build议的文本string。

当你find()锻炼你也需要填充练习。 就像是:

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