6

I have a model:

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

Want to create document like this:

{
  "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": []
        }
      ]
    }
  ]
}

According to the answer to this answer

Can be solved just by using this as a reference to the model.

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

When i try with Typescript an error will appear like:

'this' implicitly has type 'any' because it does not have a type annotation.

Any best practice to model self reference with mongoose writing on typescript.

  • the difference i see is that you're declaring with const and the example answer declared with var, perhaps? – limco Apr 09 '20 at 06:37
  • sorry I think it makes no difference, because when I try to declare it with "var" or "const", the same error will still appear. – Imanuel Pundoko Apr 09 '20 at 07:00

1 Answers1

4

You can try doing this in two steps instead with the add method:

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

schema.add({
 children: [schema]
});
johndevman
  • 183
  • 7