【问题标题】:Mongoose : Types referring to other modelsMongoose : 引用其他模型的类型
【发布时间】:2018-07-15 09:04:06
【问题描述】:

我有这个:

models/record.js

var mongoose = require("mongoose");
var RecordSchema = new mongoose.Schema({
   address : require("./address").Address
});
var Record = mongoose.model('Record', RecordSchema);
module.exports = {
   Record: Record
}

models/address.js

var mongoose = require("mongoose");
var AddressSchema = new mongoose.Schema(
{
    streetLine1: String,
    streetLine2: String,
    city: String,
    stateOrCounty: String,
    postCode: String,
    country: require("./country").Country
});
var Address = mongoose.model('Address', AddressSchema);
module.exports = {
  Address: Address
}

models/country.js

var mongoose = require("mongoose");
var CountrySchema = new mongoose.Schema({
   name: String,
   areaCode: Number
});
var Country = mongoose.model('Country', CountrySchema);
module.exports = {
   Country: Country
}

它实际上显示了这个错误:

TypeError: 未定义类型 Model country 您是否尝试过嵌套模式?您只能使用 refs 或数组进行嵌套。

我正在尝试创建一个模型,其中少数类型是另一个模型。如何存档?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-models


    【解决方案1】:

    这里的问题是您正在从 country.js 导出模型并通过在地址架构创建中的要求来使用相同的模型。创建嵌套模式时,属性的值应该是模式对象而不是模型。

    将您的 country.js 更改为:

    var mongoose = require("mongoose");
    var CountrySchema = new mongoose.Schema({
       name: String,
       areaCode: Number
    });
    module.exports = {
       Country: CountrySchema
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-23
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多