TypeScript 模式中的 Dynamoose 嵌套映射/数组

问题描述

我正在尝试为以下示例创建架构:

{
    "foods": [
        {
            "fruits": [{
                "apple": {
                    "color": "red","shape": "round"
                }
            }]
        }
    ]
}

我最初尝试执行以下结构,这在技术上是正确的,应该可以工作,但由于在 https://github.com/dynamoose/dynamoose/issues/909 中发现的错误而失败。

export const FoodsSchema = new dynamoose.Schema({
  foods: {
    type: Array,schema: [{
      type: Object,schema: {
        fruits: {
          type: Array,schema: [{
            apple: {
            type: Object,schema: {
                color: String,shape: String,},],}],});

但是它似乎不起作用。正在收到 TypeError: Cannot read property 'toLowerCase' of undefined。由于嵌套数组或对象而发生小写错误

我也看到了 TypeMismatch: Expected foods.0.fruits to be of type object,instead found type object. 后者发生在我试图改变架构时,我认为可能是这样,但这不是问题。

  • 这是使用 2.7.0 版。

解决方法

解决方案:将嵌套模式提取到它自己的模式中,并在原始模式中引用该模式。

const appleSchema = new dynamoose.Schema({
  apple: {
    type: Object,schema: {
      color: String,shape: String,},});

然后在原来的:

        fruits: {
          type: Array,schema: [appleSchema],
,

另一种选择是将您的架构更改为以下内容:

export const FoodsSchema = new dynamoose.Schema({
  foods: {
    type: Array,schema: [{
      type: Object,schema: {
        fruits: {
          type: Array,schema: [{
            type: Object,schema: {
              apple: {
                type: Object,schema: {
                  color: String,],}],});

(希望这是正确的)。

最初在 fruits schema 属性内有一个数组,然后是 apple

schema: [
  apple: {

我可能是错的,但我什至不认为这是有效的 JavaScript。

重点是,您肯定可以在 1 个模式中执行您想要执行的操作。您还可以将其分解为更小的对象而不是模式以使其更容易。

但是,正如在另一个答案中提到的,将其分解为模式也可以!

有很多不同的方法来实现这一目标。