0

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

{
    "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。
4

2 回答 2

3

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

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

然后在原来的:

        fruits: {
          type: Array,
          schema: [appleSchema],
        },
于 2021-03-11T17:27:00.987 回答
0

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

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,
                  shape: String,
              },
            },
          ],
        },
      },
    }],
  },
});

(希望这是正确的)。

最初在fruits schema属性内部你有一个数组apple

schema: [
  apple: {

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

重点是,您可以肯定地在 1 个模式中做您想做的事情。您还可以将其分解为更小的对象而不是模式,以使其更容易。

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

很多不同的方法来实现这一点。

于 2021-03-11T18:08:03.010 回答