【问题标题】:How to do mongoose model self reference on Typescript?如何在 Typescript 上做猫鼬模型自我参考?
【发布时间】:2020-07-20 23:34:10
【问题描述】:

我有一个模型:

const comment = new mongoose.Schema({
  id: { type: ObjectId, required: true },
  comment: { type: String },
  replies: [comment]
});

想要创建这样的文档:

{
  "id": 1,
  "comment": "Grand Parent Comment",
  "replies": [
    {
      "id": 11,
      "comment": "Parent Comment",
      "replies": [
        {
          "id": 111,
          "comment": "Comment",
          "replies": [
            {
              "id": 1111,
              "comment": "Child Comment",
              "replies": []
            }
          ]
        },
        {
          "id": 112,
          "comment": "Sibling Comment",
          "replies": []
        }
      ]
    }
  ]
}

根据这个answer的回答

只需使用this作为模型的参考即可解决。

  const comment = new mongoose.Schema({
    id: { type: ObjectId, required: true },
    comment: { type: String },
-   replies: [comment]
+   replies: [this]
  });

当我尝试使用 Typescript 时,会出现如下错误:

'this' 隐含类型为 'any',因为它没有类型注释。

在 typescript 上使用猫鼬书写建模自我引用的任何最佳实践。

【问题讨论】:

  • 我看到的区别是你用 const 声明而示例答案用 var 声明,也许?
  • sorry我觉得没什么区别,因为当我尝试用“var”或“const”声明时,还是会出现同样的错误。

标签: typescript mongoose mongoose-schema


【解决方案1】:

您可以尝试分两步执行此操作,而不是使用add 方法:

const schema = new mongoose.Schema({
  body: String,
});

schema.add({
 children: [schema]
});

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 2015-01-14
    • 2013-01-25
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2014-03-27
    • 2021-09-19
    相关资源
    最近更新 更多