Flukey
Flukey

Reputation: 6555

Mongoose - reference an embedded id in the parent document

I have this simple schema so far:

var room = new Schema(
  {
    name: { type: String, default: null, trim: true }
  });

var event = new Schema({
  name:            { type: String, default: null, trim: true },
  startDate:       Date,
  endDate:         Date,
  logo:            { type: Boolean, default: false },
  public:          { type: Boolean, default: false },
  rooms:           [room]
  sessions:        [
    {
      title:       { type: String, default: null, trim: true },
      description: { type: String, default: null, trim: true },
      date:        Date,
      start:       Number,
      end:         Number,
      room:        { type: Schema.Types.ObjectId, ref: 'room' }
    }
  ]
});

I know how to reference another collection but how do I reference an embedded id in the parent document?

I know this schema is not right because even If I delete a room, the room reference is not removed from a session where it is referenced.

Thanks in advance!

Upvotes: 0

Views: 956

Answers (1)

harryy000
harryy000

Reputation: 553

You could create a reference to the event in room schema.Then use the schema.pre middleware to remove the sessions.room value whenever you do a remove on the main parent room.(make sure you remove the eventid from main room schema as well).Also refer Removing many to many reference in Mongoose

var room = new Schema({
    name: {
        type: String,
        default: null,
        trim: true
    },
    eventid: {
        type: Schema.Types.ObjectId, //Set reference to event here.
        ref: 'event'
    }
});

room.pre('remove', function(next) {//event is the schema name.
    this.model('event').update({; //this will have all the models,select the event 
            sessions.room: this._id//will have the room id thats being deleted
        }, {
            $pull: {
                sessions.room: this._id//removes that array from the event.sessions.room
            }
        }, {
            multi: true
        },
        next();//continues and completes the room.remove.
    );
});

Upvotes: 2

Related Questions