{"record":{"id":"1abf018586bb5815","repo":"t8y2/dbx","slug":"each-mongodb-insertmany-document-must-be-an-object","errorCode":null,"errorMessage":"Each MongoDB insertMany document must be an object","messagePattern":"Each MongoDB insertMany document must be an object","errorType":"validation","errorClass":"java.lang.IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"agents/drivers/mongodb/src/main/java/com/dbx/agent/mongodb/MongoAgent.java","lineNumber":1480,"sourceCode":"        String docJson = params.get(\"doc_json\").getAsString();\n\n        Document doc = Document.parse(docJson);\n        c.getDatabase(database).getCollection(collection).insertOne(doc);\n        Object insertedId = convertValue(doc.get(\"_id\"));\n        return Collections.singletonMap(\"inserted_id\", insertedId);\n    }\n\n    private static Object insertDocuments(JsonObject params) {\n        String docsJson = params.get(\"docs_json\").getAsString();\n        JsonElement parsed = JsonParser.parseString(docsJson);\n        if (!parsed.isJsonArray()) {\n            throw new IllegalArgumentException(\"MongoDB insertMany documents must be a JSON array\");\n        }\n\n        List<Document> documents = new ArrayList<>();\n        for (JsonElement item : parsed.getAsJsonArray()) {\n            if (!item.isJsonObject()) {\n                throw new IllegalArgumentException(\"Each MongoDB insertMany document must be an object\");\n            }\n            documents.add(documentForWrite(item.toString()));\n        }\n        if (documents.isEmpty()) {\n            return Collections.singletonMap(\"affected_rows\", 0);\n        }\n\n        MongoClient client = requireClient();\n        String database = params.get(\"database\").getAsString();\n        String collection = params.get(\"collection\").getAsString();\n        client.getDatabase(database).getCollection(collection).insertMany(documents);\n        return Collections.singletonMap(\"affected_rows\", documents.size());\n    }\n\n    static Object parseId(String id) {\n        String stringId = decodeStringDocumentId(id);\n        if (stringId != null) {\n            return stringId;","sourceCodeStart":1462,"sourceCodeEnd":1498,"githubUrl":"https://github.com/t8y2/dbx/blob/c0390bff16418b651f4728520d99adf8ce48829a/agents/drivers/mongodb/src/main/java/com/dbx/agent/mongodb/MongoAgent.java#L1462-L1498","documentation":"insertMany validated that docs_json is an array, but at least one element of that array is not a JSON object. Every element must be a document (JSON object) that can be converted via documentForWrite; scalars or nested arrays are rejected.","triggerScenarios":"Calling insertMany with '[\"doc1\", \"doc2\"]' (strings instead of objects), '[{\"name\":\"a\"}, [1,2]]', or '[null]'. The loop throws on the first element where item.isJsonObject() is false.","commonSituations":"Pre-serializing documents to strings and then embedding those strings in the array; pipelines that mix scalars and objects; accidental use of JSON arrays of values (e.g. bulk column values) rather than arrays of documents.","solutions":["Make every element a JSON object: [{...}, {...}]","If you have pre-serialized document strings, parse each into an object before building the array","Validate array elements are objects before calling insertMany"],"exampleFix":"// before\nagent.insertMany(coll, \"[{\\\"name\\\":\\\"a\\\"}, \\\"{\\\\\\\"name\\\\\\\":\\\\\\\"b\\\\\\\"}\\\"]\");\n// after\nagent.insertMany(coll, \"[{\\\"name\\\":\\\"a\\\"}, {\\\"name\\\":\\\"b\\\"}]\");","handlingStrategy":"validation","validationCode":"const docs = JSON.parse(docsJson);\nconst bad = docs.findIndex(d => d === null || typeof d !== 'object' || Array.isArray(d));\nif (bad !== -1) throw new Error(`docsJson[${bad}] is not an object`);","typeGuard":"const isPlainObject = (d) =>\n  d !== null && typeof d === 'object' && !Array.isArray(d);","tryCatchPattern":"try {\n  agent.insertMany(coll, docsJson);\n} catch (IllegalArgumentException e) {\n  if (e.getMessage().includes(\"document must be an object\")) {\n    const fixed = JSON.parse(docsJson).map(parseIfStringDoc).filter(isPlainObject);\n    agent.insertMany(coll, JSON.stringify(fixed));\n  } else throw e;\n}","preventionTips":["Insert objects, never pre-serialized strings, into the docs array","Validate every element is a plain object before the call","Avoid mixing value arrays with document arrays in bulk paths"],"tags":["mongodb","insertmany","argument-validation"],"backgroundTag":"invalid-argument-type","analyzedSha":"c0390bff16418b651f4728520d99adf8ce48829a","analyzedAt":"2026-09-05T23:05:10.900Z","contentChangedAt":"2026-09-05T23:05:10.900Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}