Kuryaki
Kuryaki

Reputation: 1011

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 to handle either this circular schema when declaring models in mongoose or how to handle Many to Many relations.

Upvotes: 5

Views: 2563

Answers (1)

Christopher Tarquini
Christopher Tarquini

Reputation: 11342

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)

Upvotes: 8

Related Questions