我正在使用Node,Restify和Mongoose创建REST API。在尝试创建模式时,我在名为api.js
的文件中完成了以下操作:
var AddressSchema = new Schema({
address1: String,
address2: String,
city: String,
state: String,
country: String,
postalCode: String
});
var AccountSchema = new Schema({
property1: String,
property2: Number,
property3: Boolean,
owner: {
firstName: String,
lastName: String,
birthDate: Date,
ssn: String,
phoneNumber: String,
mailingAddress: AddressSchema,
physicalAddress: AddressSchema
}
});
var Account = mongoose.model("Account", AccountSchema);
然后我有各种服务器服务器,它使用mongoose模型。当我使用node api.js
运行时,出现以下错误:
C:\ yadda \ scjema.js:362个
抛出新的TypeError('未定义类型在`'+ path +TypeError:'owner.mailingAddress'的未定义类型你试过吗? 嵌套架构?您只能使用refs或数组进行嵌套 在......
我更新了架构:
mailingAddress: [AddressSchema],
physicalAddress: [AddressSchema]
现在似乎有效......但是,我并不确定这意味着什么。我不希望我的mailingAddress或physicalAddress是数组,我希望它们是单个对象。我很困惑为什么我不能简单地直接引用嵌套模式类型,如我的AddressSchema嵌套对象。唯一的另一种选择是在我的帐户架构中明确地嵌入我的地址架构,这意味着多次重复相同的代码块(我的帐户架构实际上非常大,并且有五个可能需要地址的潜在位置。)< / p>
答案 0 :(得分:0)
尝试这样做:
var AddressSchema = new Schema({
address1: String,
address2: String,
city: String,
state: String,
country: String,
postalCode: String
});
var AccountSchema = new Schema({
property1: String,
property2: Number,
property3: Boolean,
owner: {
firstName: String,
lastName: String,
birthDate: Date,
ssn: String,
phoneNumber: String,
mailingAddress: { type: AddressSchema, ref: 'AddressSchema' },
physicalAddress: { type: AddressSchema, ref: 'AddressSchema' }
}
});
var Account = mongoose.model("Account", AccountSchema);