小编Ima*_*oko的帖子

如何在 Typescript 上进行猫鼬模型自引用?

我有一个模型:

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

想要创建这样的文档:

{
  "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": []
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

根据这个答案的回答

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

{
  "id": 1,
  "comment": "Grand Parent …
Run Code Online (Sandbox Code Playgroud)

mongoose typescript mongoose-schema

6
推荐指数
1
解决办法
1184
查看次数

标签 统计

mongoose ×1

mongoose-schema ×1

typescript ×1