0
votes

I can't figure it out, hope someone is kind enough to help me.

What I basically am trying to achieve, is to have several locations, with several lessons attached to each one of it.

I have this mongoose schema:

var mongoose = require('mongoose');

var lessonNames = new mongoose.Schema({
  day: {type: String },
  name: {type: String},
  startTime: {type: String},
  endTime: {type: String}
});

var locationNames = new mongoose.Schema({
  name: {type: String, required: true},
  address: String,
  lessons: [ { type: mongoose.Schema.Types.ObjectId, ref: 'lessonnames'}]
});

mongoose.model('lessonnames', lessonNames);
mongoose.model('locationnames', locationNames);

What I already managed, is adding a lesson, and in the same process added a location, and was able to set the lesson id to the lessons ref.

But how would I add a lesson and add its id it to an already existing location? I'm able to find the right location, but I can't figure out how to add a new lesson where the lessons reference is filled with the id of the lesson.

Thank you!

2

2 Answers

0
votes

Using $push operator

var LessonNames = mongoose.model('lessonnames', lessonNames);
var LocationNames = mongoose.model('locationnames', locationNames);

new LessonNames(<lesson_object>).save(function(err, lesson){
    LocationNames.update({_id: id}, {$push: {lessons: lesson._id}}, function(err, result){

    })
})
0
votes

What have you tried so far?

After saving your lesson, you can find the location and try location.lessons.addToSet(lesson.id)

http://mongoosejs.com/docs/api.html#types_array_MongooseArray.addToSet