{"record":{"id":"6be8817c30792a1d","repo":"elsa-workflows/elsa-core","slug":"document-id-is-required","errorCode":null,"errorMessage":"Document ID is required.","messagePattern":"Document ID is required\\.","errorType":"validation","errorClass":"DocumentStoreValidationException","httpStatus":null,"severity":"error","filePath":"src/modules/Elsa.Persistence.VNext.MongoDb/MongoDbDocumentStore.cs","lineNumber":151,"sourceCode":"        return _database.GetCollection<BsonDocument>(collectionPlan.CollectionName);\n    }\n\n    private async Task EnsureCollectionExistsAsync(string collectionName, CancellationToken cancellationToken)\n    {\n        using var cursor = await _database.ListCollectionNamesAsync(new ListCollectionNamesOptions\n        {\n            Filter = new BsonDocument(\"name\", collectionName)\n        }, cancellationToken);\n\n        var exists = await cursor.MoveNextAsync(cancellationToken) && cursor.Current.Any();\n        if (!exists)\n            await _database.CreateCollectionAsync(collectionName, cancellationToken: cancellationToken);\n    }\n\n    private static void ValidateSaveRequest(DocumentCollection collection, SaveDocumentRequest request)\n    {\n        if (string.IsNullOrWhiteSpace(request.Id))\n            throw new DocumentStoreValidationException(\"Document ID is required.\");\n\n        var missingFields = collection.Indexes\n            .SelectMany(x => x.Fields)\n            .Distinct(StringComparer.Ordinal)\n            .Where(field => !request.IndexValues.ContainsKey(field))\n            .Order(StringComparer.Ordinal)\n            .ToList();\n\n        if (missingFields.Count > 0)\n            throw new DocumentStoreValidationException($\"Storage unit '{collection.Name}' requires index values for fields '{string.Join(\", \", missingFields)}'.\");\n    }\n\n    private static void ValidateExpectedVersion(string storageUnit, string documentId, long? expectedVersion, long? actualVersion)\n    {\n        if (expectedVersion is null)\n            return;\n\n        if (expectedVersion != (actualVersion ?? 0))","sourceCodeStart":133,"sourceCodeEnd":169,"githubUrl":"https://github.com/elsa-workflows/elsa-core/blob/fe9217bdfa0e27f0e09e45006eb6898f616e513d/src/modules/Elsa.Persistence.VNext.MongoDb/MongoDbDocumentStore.cs#L133-L169","documentation":"MongoDbDocumentStore.SaveAsync validates every save request before touching MongoDB. If the request's Id is null, empty, or whitespace it throws DocumentStoreValidationException, because the document's Id becomes the MongoDB _id key and cannot be defaulted. The library refuses to generate an Id on your behalf.","triggerScenarios":"Calling SaveAsync with a SaveDocumentRequest whose Id property is null, empty string, or whitespace-only — typically when a caller forgot to assign Id before saving a new document.","commonSituations":"Constructing SaveDocumentRequest from user input or an API payload where the client omitted the Id; deserializing a request model where Id wasn't mapped; generating documents in a loop where only the first had an assigned Id.","solutions":["Assign a valid non-empty Id to SaveDocumentRequest.Id before calling SaveAsync (e.g. Guid.NewGuid().ToString()).","Validate the request in your own layer before invoking the store so callers get a clear error about the missing Id.","If Ids should be generated automatically, generate them at the source that builds SaveDocumentRequest; the store does not do this for you."],"exampleFix":"// before\nvar request = new SaveDocumentRequest { Collection = \"orders\", IndexValues = indexValues };\nawait store.SaveAsync(collection, request, ct);\n\n// after\nvar request = new SaveDocumentRequest { Id = Guid.NewGuid().ToString(), Collection = \"orders\", IndexValues = indexValues };\nawait store.SaveAsync(collection, request, ct);","handlingStrategy":"validation","validationCode":"if (string.IsNullOrWhiteSpace(request.Id))\n    throw new ArgumentException(\"Document ID must be set before saving.\", nameof(request));","typeGuard":"static bool HasValidId(SaveDocumentRequest r) => !string.IsNullOrWhiteSpace(r.Id);","tryCatchPattern":"try\n{\n    await store.SaveAsync(collection, request, ct);\n}\ncatch (DocumentStoreValidationException ex)\n{\n    logger.LogError(ex, \"Invalid save request for collection {Collection}\", collection.Name);\n    throw;\n}","preventionTips":["Always assign an Id (e.g. Guid.NewGuid().ToString()) at the point where SaveDocumentRequest is constructed.","Validate incoming payloads map an Id before building the request.","Add a unit test asserting requests without Ids are rejected in your own layer."],"tags":["mongodb","validation","persistence","missing-id"],"backgroundTag":"missing-required-argument","analyzedSha":"fe9217bdfa0e27f0e09e45006eb6898f616e513d","analyzedAt":"2026-09-13T20:32:34.702Z","contentChangedAt":"2026-09-13T20:32:34.702Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}