Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

381
Visualizações
How to store enum as string instead of int in Mongodb

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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(),
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda