mongodbspring-bootmongodb-querydbref

referencing a MongoDB collection using @DBRef annotation inside a list of custom object(DTO) but refence value coming as null


I have a model class

AssessmentTemplate

which is like this.

public class AssessmentTemplate {

@Field("_id")
@Id
private String assessmentId;
private Date creationDate;
private String type;
private String status;
@Field("coreQuestions")
private QuestionTemplate[] coreQuestions;
@Field("baseQuestions")
private QuestionsTemplate[] baseQuestions;
} 

This is having a nested array of object of

QuestionsTemplate which is like this

public class QuestionsTemplate {
@DBRef
private Question questionsId;
private int score;
}

question

public class Question {
@Id
private String id;
private String name;
@DBRef
private List<Option> options;

}

On querying question, option reference data is getting loaded fine

On Mongo Side-I have a collection of question and assessment template.

While querying data for assessment I am not getting data of question in JSON

need inputs where I might be going wrong. Do request if any more information is needed.

Disclaimer-data added in mongo is through manual JSON input and not through REST endpoint.


Solution

  • the issue was not at the java end but on the mongo-end. the place where I was referencing to question collection I was passing id as

    "question":{
    "$ref":"question",
    "$id":"640b87a5dd7cbc1dac84d65a"
    }
    

    instead of that what worked for me is

    "question": {
    "$ref": "question",
    "$id": {
    "$oid": "640b87a5dd7cbc1dac84d65a"
    }
    }