Mongoose :引用其他模型的类型

Mongoose : Types referring to other models

我有这个:

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:未定义类型 Modelcountry 你试过嵌套模式吗?您只能使用引用或数组进行嵌套。

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

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

将您的 country.js 更改为:

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