猫鼬:指其他模型的类型

时间:2018-02-05 13:31:59

标签: node.js mongodb mongoose mongoose-schema mongoose-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
}

模型/ 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
}

模型/ 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   你尝试过嵌套Schemas吗?您只能使用refs或数组进行嵌套。

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

1 个答案:

答案 0 :(得分:2)

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

将您的country.js更改为:

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