Issue while updating a document


I tried to make some sort of Update method that I can use it in my multiple repositories/handlers to update a document.

For some reason, when I try to do the update, my user is not found, even though the id is present in the DB.

Here is my code:

 public async Task<ErrorOr<long>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
     var identity = _contextAccessor.HttpContext.User.Identity as ClaimsIdentity;

     var id = identity!.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)!.Value;

     if (id == null)
         return User.Errors.UserNotFound;

     var filter = Builders<BsonDocument>.Filter.Eq("_id", id);
     var entity = await _userCollection.Find(filter).FirstOrDefaultAsync();

     var result = await UpdateCommand(id, request);

     return 0;

 private async Task<UpdateResult> UpdateCommand<T>(string documentIdentifier, T command)
     var filter = Builders<BsonDocument>.Filter.Eq("_id", documentIdentifier);
     var updateDefinitionBuilder = Builders<BsonDocument>.Update;

     var changesDocument = BsonDocument.Parse(JsonSerializer.Serialize(command));
     var updateDefinitionList = new List<UpdateDefinition<BsonDocument>>();

     foreach (var change in changesDocument)
         var setDefinition = updateDefinitionBuilder.Set(change.Name, change.Value);

     var combinedUpdateDefinition = updateDefinitionBuilder.Combine(updateDefinitionList);

     return await _userCollection.UpdateOneAsync(filter, combinedUpdateDefinition);

And here is how my document looks like:

    "_id" : ObjectId("65b118b74c717d9c9919faf7"),
    "CreatedDateTime" : ISODate("0001-01-01T00:00:00.000+0000"),
    "UpdatedDateTime" : ISODate("0001-01-01T00:00:00.000+0000"),
    "FirstName" : "andrei",
    "LastName" : "costache",
    "Email" : "",
    "Password" : "string",
    "ProfileImage" : null,
    "RefreshTokens" : [
            "Token" : "xuGy+cn6AKOgeKAAnEopnfRsWj0ieiMlmiVgF76NKzJjAyRqYHFew3LWjBeSa9sw0uFBFlDDashS1rXGFNElPQ==1706120675",
            "ExpiresOn" : ISODate("2024-01-31T18:24:35.145+0000"),
            "IsActive" : true
            "Token" : "0tSuCy//9+QYEpGKR+EchrDZKqC2T04en/hIXdI92jP9lRsAmFLY5qjyKXlJaU5ZmzZTkaZDD7h+Juul53nXkg==1706186538",
            "ExpiresOn" : ISODate("2024-02-01T12:42:18.937+0000"),
            "IsActive" : true
    "UserType" : "Guest",
    "UserRole" : "User"

Can someone help me.

Thank you very much.

PS: Just a beginner on MongoDb

To have a match the type and value have to be the same. The stored _id is an ObjectId and you are passing a string.

Thank you very much, good sir!

Have a beautiful day!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.