Is it somehow possible to overcome the "Cannot write to a computed field" constraint?

Is it somehow possible to overcome the “Cannot write to a computed field” constraint?

We would like to achieve that if a chapter contains a masterChapter, the chapter title will be computed from masterChapter.title. But if it doesn’t contain a masterChapter, it should use the chapter title. For that, we would like to be able to write/create chapter as part of chapters, but this is currently throwing a “Cannot write to a computed field”.

Collection.byName("Document")!.update({
  computed_fields: {
    chapters: { 
        body: "doc => {
        doc.chapters.map((chapter) => {
          if(chapter.masterChapter != null) {
            {
              title: chapter.masterChapter.title,
              masterChapter: chapter.masterChapter
            }
          } else {
            chapter
          }
        })
      }",
      signature: "Array" 
    }
  }
})

Example document structure

Document.create({
  chapters: [
    {
      title: "This title should be seen"
    },
    {
      title: "This title should never be seen!",
      masterChapter: MasterChapter.byId("390327058219139280"),
    },
  ]
})

If you could persist a field with the same name as a computed field then we wouldn’t be able to tell the difference which one you wanted.

You can use calculated fields in other calculated fields, so we also don’t want to make field selection a special thing within a calculated field. Your example is attempting a kind of infinite recursion by defining a computed field called chapters which references a field on the doc called chapters. We are working on explicitly disallowing this, since there is no way for a recursive computed field to ever reach a base case, i.e. it will continue recursing until it hits a stack overflow.

Would it help you if you did a one-time migration to provide default values for the title?

Otherwise, it seems like your best bet might be a third field, which is the computed field based on the two persisted fields.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.