How to create nested computed fields?

You can’t inject computed fields into nested arrays or objects. You can create new objects from existing ones, though.

collection Plan {
  history_days 0
  
  // defining schema fields requires early access at the moment (*)
  // a field for "internal use only"
  _chapter: { title: String, /* ... */ }

  compute chapter = doc => Object.assign(doc.chapter, {
    attachments: Attachment.by_chapter(doc.chapter.title).toArray().map(.fileName)
    /*... more fields */
  })
}

Are you trying to handle relationships to a nested object (like my example assumes), or trying to effectively backfill part of your schema, or what are you trying to accomplish otherwise? Why must the attachments be nested under the chapter field?


(*)

To migrate from a schema like this

collection Plan {
  history_days 0
  
  chapter: { title: String }
}

could be update like this

collection Plan {
  history_days 0
  
  // a field for "internal use only"
  _chapter: { title: String }

  compute chapter = doc => Object.assign(doc.chapter, {
    attachments: Attachment.by_chapter(doc.chapter.title).toArray().map(.fileName)
  })

  migration m2024_04_25_new_chapter_format {
    rename chapter _chapter
  }
}