1

I am generating models to be saved in MongoDB using protobuf java. I want to generate a custom _id field.

Can anyone let me how to achieve this?

I have tried adding the _id field, but it is not working as expected.

syntax = "proto3";
message User {
    string first_name = 1;
    string last_name = 2;
    int64 dob = 3; // dob in the epoch format
    int64 phone = 4;
    string email = 5;
    string type = 6;
    string role = 7;
    string user_id = 8;
    bytes password = 9;
    bool is_active = 10;
    Meta meta = 11;
    AddViaEnum addedVia = 12;
    Address address = 13;
    int64 _id = 14;
}

Please find below the code to connect to MongoDB and inserting the document.

@Slf4j
public class CrudDaoImpl implements CrudDao {

private MongoClient mongoClient;
private MongoDatabase mongoDatabase;

@Inject
public CrudDaoImpl(MongoClient mongoClient) {
    this.mongoClient = mongoClient;
    this.mongoDatabase = this.mongoClient.getDatabase("test");
    log.info("Connected to database");
}

@Override
public void saveDocument(String collectionName, String request) throws IOException {
    MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
    collection.insertOne(Document.parse(request));
  }
}

I am using google guice for dependency injection. Initializing mongo client as below

@Provides
public MongoClient get() {
    return MongoClients.create("mongodb://localhost:27017");
}

After inserting the document in the mongodb through the java application with the above set-up, mongo is creating ObjectID as the _id. I wanted custom generated _id and I am not sure how to define that in protobuf.

0 Answers0