Circular Reference with mongoose


I have the following code for mongoose schemas

var EstacionSchema = new Schema({
    nombre          : {type : String, required: true, unique: true}
  , zona            : {type : String, required: true}
  , rutas           : [Ruta]
})

mongoose.model('Estacion', EstacionSchema)

var RutaSchema = new Schema({
    nombre          : {type : String, required: true, unique: true, uppercase: true}
  , estaciones      : [Estacion]
})

mongoose.model('Ruta', RutaSchema)

however when i try it it shows

ReferenceError: Ruta is not defined

I am not sure how yo handle either this circular schema when declaring models in mongoose or handle Many to Many relations



First off you are referencing variables that don't exist. You'd reference it via RutaSchema or mongoose.model('Ruta');.

I'd try

var EstacionSchema = new Schema({
    nombre          : {type : String, required: true, unique: true}
  , zona            : {type : String, required: true}
})

mongoose.model('Estacion', EstacionSchema)

var RutaSchema = new Schema({
    nombre          : {type : String, required: true, unique: true, uppercase: true}
  , estaciones      : [EstacionSchema]  // or mongoose.Model('Estacion');
})

// Add reference to ruta
EstacionSchema.add({rutas: [RutaSchema]});
mongoose.model('Ruta', RutaSchema)