{"record":{"id":"b900a2220f846f6d","repo":"Automattic/mongoose","slug":"cannot-manually-populate-single-nested-subdoc-unde","errorCode":null,"errorMessage":"Cannot manually populate single nested subdoc underneath Map at path \"${this.$__path}\". Try using an array instead of a Map.","messagePattern":"Cannot manually populate single nested subdoc underneath Map at path \"(.+?)\"\\. Try using an array instead of a Map\\.","errorType":"exception","errorClass":"MongooseError","httpStatus":null,"severity":"error","filePath":"lib/types/map.js","lineNumber":116,"sourceCode":"    // you can't get access to `$__schemaType` to cast in the initial call to\n    // `set()` from the `super()` constructor.\n\n    if (this.$__schemaType == null) {\n      this.$__deferred = this.$__deferred || [];\n      this.$__deferred.push({ key: key, value: value });\n      return;\n    }\n\n    let _fullPath;\n    const parent = this.$__parent;\n    const populated = parent?.$__?.populated ?\n      parent.$populated(fullPath.call(this), true) || parent.$populated(this.$__path, true) :\n      null;\n    const priorVal = this.get(key);\n\n    if (populated != null) {\n      if (this.$__schemaType.$isSingleNested) {\n        throw new MongooseError(\n          'Cannot manually populate single nested subdoc underneath Map ' +\n          `at path \"${this.$__path}\". Try using an array instead of a Map.`\n        );\n      }\n      if (Array.isArray(value) && this.$__schemaType.$isMongooseArray) {\n        value = value.map(v => {\n          if (v.$__ == null) {\n            v = new populated.options[populateModelSymbol](v);\n          }\n          // Doesn't support single nested \"in-place\" populate\n          v.$__.wasPopulated = { value: v._doc._id };\n          return v;\n        });\n      } else if (value != null) {\n        if (value.$__ == null) {\n          value = new populated.options[populateModelSymbol](value);\n        }\n        // Doesn't support single nested \"in-place\" populate","sourceCodeStart":98,"sourceCodeEnd":134,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/types/map.js#L98-L134","documentation":"Thrown by MongooseMap.$__set() when a Map path is populated and you assign into it, and the Map's values are single nested subdocuments. Mongoose supports in-place populate casting only for arrays of subdocs; a populated single-nested value inside a Map cannot be cast, so it asks you to change the schema shape.","triggerScenarios":"Schema: { refs: { type: Map, of: new Schema({ ... }) } } (single nested values), followed by await doc.populate('refs') and then doc.refs.set('key', { ... }) on the populated map.","commonSituations":"Modeling keyed relationships as Map of subdocs instead of arrays, then trying to populate and mutate in place.","solutions":["Change the field to an array of subdocuments: { type: [{ type: SubSchema, ref: 'Model' }] } and populate normally","Keep the Map of plain _ids ({ type: Map, of: ObjectId }) and populate through a virtual or manual lookup","Avoid writing to the Map while it is populated — depopulate or rebuild the document first"],"exampleFix":"// before\nconst s = new Schema({ refs: { type: Map, of: new Schema({}, { _id: false }) } });\n// after\nconst s = new Schema({ refs: [{ type: Schema.Types.ObjectId, ref: 'Other' }] });","handlingStrategy":"validation","validationCode":"const RESERVED = new Set(['__proto__', 'constructor', 'prototype']);\nfunction mapSet(map, key, value) {\n  const k = String(key);\n  if (k.startsWith('$') || k.includes('.') || RESERVED.has(k)) throw new Error(`Invalid map key: ${k}`);\n  map.set(k, value);\n}","typeGuard":"function isSingleNestedMap(schemaType) {\n  return schemaType.$isMongooseMap && schemaType.$__schemaType?.$isSingleNested === true;\n}","tryCatchPattern":"try { doc.refs.set(key, val); } catch (err) { if (/single nested subdoc underneath Map/.test(err.message)) throw new Error('Schema change required: use an array of subdocs instead of Map for this path'); throw err; }","preventionTips":["Do not combine populate with Maps of single nested subdocs — model them as arrays","Store plain ObjectIds in Maps and resolve relations via separate queries or virtuals","Document the limitation in schema review checklists for populated paths"],"tags":["mongoose","map","populate","single-nested"],"backgroundTag":"unsupported-populate-call","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}