Ticket: User Management -> LoginUserAsync -> Upsert doesn't update/insert

I completed the method. It passed the unit test. But then I tried running the test again and now it’s failing.
Debugging what’s wrong: The result is that it’s not updating the existing user. Instead it throws an exception.

MongoDB.Driver.MongoWriteException: ‘A write operation resulted in an error.
E11000 duplicate key error collection: 61b087f5f9b80b70983a9e44_sample_mflix.sessions index: user_id_1 dup key: { user_id: null }’


                var sessionFilter = Builders<Session>.Filter.Eq(s => s.UserId, user.Email);

                await _sessionsCollection.UpdateOneAsync(
                    Builders<Session>.Update.Set(s => s.UserId, user.Id).Set(s => s.Jwt, user.AuthToken),
                    new UpdateOptions() { IsUpsert = true },

The code looks fine to me. As far as I understand upsert is either updating the existing document or inserting a new one.

Yes. Typical. Post a question and immediately find an answer.
Thank you for being my rubber duck :wink:
I was setting Session’s property “UserId” to User’s Id instead of Email.

1 Like

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