Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Kuryaki Avatar asked Apr 05 '12 06:04

Kuryaki


1 Answers

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)
like image 81
Christopher Tarquini Avatar answered Nov 13 '22 06:11

Christopher Tarquini