0

Hello i'm trying to retrive the roles of user witch are based on another document, I have the referens of this roles in the user document as a list of objects

i get a mistake when this is excuted

List<Document> listRoles = (List<Document>) document.get("listRole");

com.mongodb.DBRef cannot be cast to org.bson.Document

{
    "_id" : ObjectId("5a8bf269e1147736b4a7d06c"),
    "_class" : "fr.anasys.testsecuritymongodb.models.User",
    "username" : "hamou",
    "password" : "amroun",
    "actived" : true,
    "listRole" : [ 
        {
            "$ref" : "role",
            "$id" : ObjectId("5a8bf269e1147736b4a7d06a")
        }, 
        {
            "$ref" : "role",
            "$id" : ObjectId("5a8bf269e1147736b4a7d06b")
        }
    ]
}


    MongoDatabase database = mongoClient.getDatabase("rdproject2");
    MongoCollection<Document> collection = database.getCollection("User");

    Document document = collection.find(Filters.eq("username",email)).first();

    if(document!=null) {

        String username = document.getString("username");
        String password = document.getString("password");
        boolean actived = document.getBoolean("actived");
        List<Document> listRoles = (List<Document>) document.get("listRole");

        List<RefId> listRefIds = new ArrayList<>();

        for (Document refId :listRoles ) {
           listRefIds.add(new RefId(refId.getString("ref"),refId.getString("id" )));

        }
Christoph Strobl
  • 6,491
  • 25
  • 33
hamou amroun
  • 1
  • 1
  • 2

1 Answers1

0

According to Resolve DBRef into Json you can decode the document to JSON.

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry());
final DocumentCodec codec = new DocumentCodec(codecRegistry, new BsonTypeClassMap());
--------
String docJson = document.toJson(codec);

Then you can parse from the JSON to get the id fields. This might not be the best way to resolve the problem but this is what I'm doing now.