"_id" field mapped to null || PojoCodecRegistry

Hi,

  1. I am using PojoCodecRegistry (BSON library) and need to map the the "_id " field of the Mongo DB document to user defined POJO field.

  2. However, the “_id” field is getting mapped to null. I have a property named as :

  3. I am using mongo java 4.0 driver and JAVA 8

1 Like

Hello Aditya,

Can you provide details about how you are mapping the _id field - please include your Pojo class with the _id field mapping.

Also, please include code you had tried to build the Pojo object and insert into the collection.

Thanks So very much for acknowledging the concern.
The POJO class is something like below ::

package org.mongo;

//imports

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Student {
public Student() {
}

@BsonProperty("_id")     
@JsonProperty("_id")
private ObjectId _id;

private String name;
private int age;
private int courseCount;
private String email;
private boolean isVerified;
private ArrayList<String> hobbies;
private ContactDetails contactDetails;
private ArrayList<Marks> marks;

// Getters and Setters

// toString() method

}

Basically this error is occurring when the BSON is deserialized to Java Object. _id field is mapped to null. Rest all other fields are mapped properly.

Please let me know how to solve this problem.

1 Like

The Pojo class is good.

You can create Pojo objects and insert into a MongoDB collection as documents and retrieve them - without problem. All this using the default driver created ObjectId.

You can post the code related with creating the object (new Student(), setting the properties, etc.,), how you are inserting and retrieving.

Also, see code examples at: MongoDB Java Driver - POJOs.

Is there any solution for the above issue I have the same problem too. Thanks

Please use @BsonId and ObjectId along with fieldName ‘id’ you will get the objectId

some thing like

@BsonId
private ObjectId id;

reason is by default Bson will be using ‘_’ as word saparator of database feilds like below
lets take an example
DB field user_id
Pojo class userId then it will map to it.

It is working for me , hope will help you as well.

1 Like