Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

MongoDB/mongoose creating a relation between two models?

I am looking to create a one-to-many relationship following this pattern http://docs.mongodb.org/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/

I have an Exercise.js schema, which will contain a collection of exercises.

var exerciseSchema = new mongoose.Schema({

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

});

Then I have a workout plan BeginnerWorkout.js schema

var workoutDaySchema = new mongoose.Schema({

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

});

I want to associate an array of exercises to the workoutDaySchema, this contains a collection of workout days for a particular workout, each day has a collection of exercises.

I have a seeder function that generates the workout for me.

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

}

So my question is inside building a workout plan, how can I associate the exercises into the exercises key using mongoose?

Upvotes: 1

Views: 2004

Answers (1)

Daniel Flippance
Daniel Flippance

Reputation: 7932

Try this:

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

And add an exercise to the workout using the exercise._id (In your code above you'd need to put this in the relevant callback such as the callback for .save on the exercise):

newDay.exercises.push(newExercise._id);

_id is generally a generated number so I don't know if you can set it to the text string you suggest.

When you .find() a workout you'll need to populate the exercises too. Something like:

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

Upvotes: 1

Related Questions