javascript - Mongoose 的循环引用

标签 javascript node.js mongoose

我有以下 Mongoose 模式代码

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)

但是当我尝试它时它显示

ReferenceError: Ruta is not defined

我不确定在 mongoose 中声明模型时如何处理这种循环模式或如何处理多对多关系。

最佳答案

首先,您引用了不存在的变量。您可以通过 RutaSchemamongoose.model('Ruta'); 引用它。

我会试试

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)

关于javascript - Mongoose 的循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10023624/

相关文章:

javascript - Angular:将通过 API 检索到的 JSON 对象的数组分配给变量

javascript - 在 IE 中设置边框的不透明度(version<=8)

node.js - expo publish 总是以 Ubuntu 上的 Javascript head out of memory 结束

javascript - 有没有办法记录 npm install 命令的输出

node.js - 使用node.js查询mongoDB的特定字段

javascript - 使用 splice 方法时如何保留先前的数组

javascript - 使用 JavaScript 更改整个页面的前景色和背景色

java - 适合网络分析的数据库?

javascript - TextEncoder 未定义。使用 nodejs 在 wsl2 上连接到 MongoDB

node.js - 未创建 Mongoose 复合索引(太长)