{"record":{"id":"06dfeb95dc352d86","repo":"hcengineering/platform","slug":"document-not-found-json-stringify-query","errorCode":null,"errorMessage":"Document not found: ${JSON.stringify(query)}","messagePattern":"Document not found: (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"server/tool/src/initializer.ts","lineNumber":220,"sourceCode":"  }\n\n  private async processImport (step: ImportStep, vars: Record<string, any>, logger: ModelLogger): Promise<void> {\n    try {\n      const uploader = new StorageFileUploader(this.ctx, this.storageAdapter, this.wsIds)\n      const initPath = path.resolve(this.initRepoDir, step.path)\n      const importer = new HulyFormatImporter(this.client, uploader, logger, vars)\n      await importer.importFolder(initPath)\n    } catch (error) {\n      logger.error('Import failed', error)\n      throw error\n    }\n  }\n\n  private async processFind<T extends Doc>(step: FindStep<T>, vars: Record<string, any>): Promise<void> {\n    const query = this.fillProps(step.query, vars)\n    const res = await this.client.findOne(step._class, { ...(query as any) })\n    if (res === undefined) {\n      throw new Error(`Document not found: ${JSON.stringify(query)}`)\n    }\n    if (step.resultVariable !== undefined) {\n      vars[`\\${${step.resultVariable}}`] = res\n    }\n  }\n\n  private async processMixin<T extends Doc>(step: MixinStep<T, T>, vars: Record<string, any>): Promise<void> {\n    const data = await this.fillPropsWithMarkdown(step.data, vars, step.markdownFields)\n    const { _id, space, ...props } = data\n    if (_id === undefined || space === undefined) {\n      throw new Error('Mixin step must have _id and space')\n    }\n    await this.client.createMixin(_id, step._class, space, step.mixin, props)\n  }\n\n  private async processUpdate<T extends Doc>(step: UpdateStep<T>, vars: Record<string, any>): Promise<void> {\n    const data = await this.fillPropsWithMarkdown(step.data, vars, step.markdownFields)\n    const { _id, space, ...props } = data","sourceCodeStart":202,"sourceCodeEnd":238,"githubUrl":"https://github.com/hcengineering/platform/blob/63e28dc96483967b2fc21c881b3f1023c1de7718/server/tool/src/initializer.ts#L202-L238","documentation":"The initializer's processFind step resolves a FindStep by running findOne against the target client; findOne returning undefined means no document matched the (variable-filled) query. The step cannot continue because later steps may reference the found document via its result variable, so the initializer fails fast. This is a data/precondition mismatch: the script expects a document that does not exist in this workspace.","triggerScenarios":"Running an init/update script whose FindStep query matches nothing: the document was renamed, deleted, was created by a previous skipped step, or the query has wrong values after fillProps variable substitution.","commonSituations":"Re-running init scripts on a workspace where the target document's _id/space differs; script written against demo/seed data that is absent; typo in query fields or a _class mismatch; version upgrade where the referenced object no longer exists.","solutions":["Verify the document exists with a matching query (check _id, space, _class, and filter fields) in the target workspace.","Fix the FindStep query in the script, or add a preceding Create/Update step ensuring the document exists before find.","Make the step tolerant: check res === undefined and skip or create the document instead of failing when the find is optional."],"exampleFix":"// before\nconst res = await this.client.findOne(step._class, { ...(query as any) })\nif (res === undefined) throw new Error(`Document not found: ${JSON.stringify(query)}`)\n// after\nconst res = await this.client.findOne(step._class, { ...(query as any) })\nif (res === undefined) return // optional find: nothing to bind to resultVariable","handlingStrategy":"validation","validationCode":"const existing = await client.findOne(step._class, step.query as any)\nif (existing === undefined) {\n  console.error(`FindStep will fail: no ${step._class} matching`, step.query)\n}","typeGuard":"function isFound<T extends Doc>(doc: T | undefined): doc is T {\n  return doc !== undefined\n}","tryCatchPattern":"try {\n  await initializer.processScript(ctx, script)\n} catch (err) {\n  if ((err as Error).message.startsWith('Document not found:')) {\n    console.error('Fix the FindStep query or ensure the document is created first:', err.message)\n  }\n  throw err\n}","preventionTips":["Ensure a Create/Update step runs before any FindStep referencing the document.","Validate queries against the target workspace before running init scripts.","Check that ${var} placeholders in queries are bound by earlier steps.","Re-check scripts after upgrades that rename or remove documents."],"tags":["initialization","find","missing-document"],"backgroundTag":"document-not-found","analyzedSha":"63e28dc96483967b2fc21c881b3f1023c1de7718","analyzedAt":"2026-08-29T15:21:27.377Z","schemaVersion":2},"datasetVersion":"2026-08-29T17:17:51.833Z"}