我希望按照这个模式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键使用猫鼬演习?
发布于 2015-08-09 07:01:07
试试这个:
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) {
//etchttps://stackoverflow.com/questions/31900673
复制相似问题