1

I am using grpc+golang+mongodb, and I have the following proto file.

enum InventoryType {
    LARGE = 0;
    SMALL = 1;
}

my go code:

import (
    "context"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"

    "inventory-service/pb"
)

func (i *Inventory) CreateInventory(ctx context.Context, req *pb.CreateInventoryRequest) (*pb.CreateInventoryResponse, error) {
    inventory := req.GetInventory()

    data := pb.Inventory{
        Inventory: inventory.GetInventory(),
    }

    mctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

    collection := client.Database("test_db").Collection("test_collection")
    collection.InsertOne(mctx, data)

    return &pb.CreateInventoryResponse{}, nil
}

and when I save the enum to mongodb using golang, it saves the int value 0, 1 instead of 'LARGE', 'SMALL', any ideas on how I can save string instead?

1 Answer 1

3

Protobuf is for communication, not for database modeling. You shouldn't use protobuf generated files to save in your database.

Instead create a separate type that models the document you want to store in the database, in which you may store the string representation of your enum, and that will get stored in the database.

For example:

type MyData {
    Inventory string `bson:"inventory"`
}

And using it:

data := MyData{
    Inventory: inventory.GetInventory().String(),
}
3
  • What is the standard way to do this, because I do see google official doc using generated code for modelling, developers.google.com/protocol-buffers/docs/gotutorial. Feb 2, 2021 at 8:05
  • Also, if i create separate models, ex, I have 2 micro services, User and Inventory, and if Inventory depends on User, does that mean I need to create my own User model twice in both Inventory and User? Feb 2, 2021 at 8:07
  • Yes, it's used for modeling, but not database objects but data for communication.
    – icza
    Feb 2, 2021 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.