我的结构如下:
--> means is included in (as property):
Item --> ItemStack <--> Inventory
Item: name: string, weight: number, ...
ItemStack: item: Item, amount: number, inventory: Inventory | null
Inventory: items: ItemStack[], capacity: number
物料是某些物料的一般定义。
ItemStack引用了该项目以及其中有多少个项目。但是,一个项目可以是一个背包,一个背包可以有一个清单。因此,ItemStack还具有一个清单作为子文档。然后,库存存储一个ItemStacks数组。这就是问题所在,因为ItemStack和Inventory不应具有自己的集合,因为它们不在多对多关系中,所以最好将它们存储为子文档。问题来了,因为这可能被视为循环引用,但是永远不会发生。
这就是它的实际效果(从数据库中检索时):
Item {
id: 1,
name: "Apple",
weight: 1
}
Item {
id: 2,
name: "Backpack",
weight: 10
}
InventoryHolder {
Inventory {
capacity: 10,
items: [
Item {
id: 1,
name: "Apple"
},
Item {
id: 2,
name: "Backpack",
inventory: Inventory { // the point of circular reference
items: [] // as many more items in backpacks as needed
}
}
]
}
}
但是,由于库存只能由一个所有者或物品持有或拥有,因此最好将它们存储为子文档。
我现在的问题是如何为结构定义模型,使其像这样工作。
提前致谢!
编辑:
我尝试使用Typegoose,它可以让我定义模型的类。
根据将它们作为子文档的方式,这就是我尝试设置它们的方式:
class TSItem extends Typegoose {
@prop()
name?: string;
@prop()
weight?: number;
@prop()
canHaveInventory?: boolean;
}
class TSItemStack extends Typegoose {
@prop()
item?: TSItem;
@prop()
inventory?: TSInventory;
@prop()
amount?: number;
}
class TSInventory {
items?: TSItemStack[];
capacity?: number;
constructor(){
this.items = [];
this.capacity = 10;
}
}
但是,在编译时,显然会出现此错误:
ReferenceError: TSInventory is not defined
...因为我想在定义它之前使用它。这就是确切的问题。类型本身是循环关系,但是当将其与实际数据一起应用时,这种情况永远不会发生。
最佳答案
设法简单地使用“对象”作为递归/循环引用的类型。
之后将要求我进行一些类型转换,但是可以!
似乎无法以其他任何方式解决问题。