最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Circular Reference with mongoose - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Nov 17, 2021 at 21:40 Inigo 15.2k5 gold badges50 silver badges82 bronze badges asked Apr 5, 2012 at 6:25 KuryakiKuryaki 1,0112 gold badges10 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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)
发布评论

评论列表(0)

  1. 暂无评论