Not able to cast result of find query to model class - 'Session' object

In user management ticket -
While implementing getUserSession():Session method, I am using a find() query and its result I have to put into Session class object and then return this object. While doing so, I am getting error -
Error:(104, 92) java: incompatible types: org.bson.Document cannot be converted to mflix.api.models.Session

While implementing getUser():User method, I have written same thing - I used find() query and put its result directly into User class object and it ran successfully but in getUserSession() I am getting error.

Refer screenshot in which you can see how I wrote code for User object and Session object -

Steve’s reply in this link may help
Please check

Chapter 2: User management ticket - currently validating

No. I am not able to resolve this issue and don’t know what needs to be done. Please help

Hi @Sparsh_94744,

Please make sure that sessionsCollection is of Sessions type and not Document type.
Edit the declaration of sessionsCollection to below:
private final MongoCollection<Session> sessionsCollection;

If you get any error in any other line, please share the screenshot of the same.

Thanks,
Sonali

My UserTest are passing from IDE but when I run User Management from status page I get following Exception in createUserSession

java.lang.ClassCastException: mflix.api.models.Session cannot be cast to org.bson.Document

The code for the function is

Session session = new Session();
session.setJwt(jwt);
session.setUserId(userId);
sessionsCollection.insertOne(session);
return true;

I have also made changes like

private final MongoCollection<Session> sessionsCollection;
       CodecRegistry pojoCodecRegistry =
                fromRegistries(
                        MongoClientSettings.getDefaultCodecRegistry(),
                        fromProviders(PojoCodecProvider.builder().automatic(true).build()));

sessionsCollection = db.getCollection("sessions", Session.class).withCodecRegistry(pojoCodecRegistry);

Not sure why the tests from status page is throwing error when the tests pass

Please provide the stack trace of the ClassCastException.

The issue was resolved after application restart

1 Like