【问题标题】:How to store enum as string instead of int in Mongodb如何在Mongodb中将枚举存储为字符串而不是int
【发布时间】:2021-02-02 05:40:44
【问题描述】:

我正在使用grpc+golang+mongodb,并且我有以下proto 文件。

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

我的代码:

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
}

当我使用 golang 将枚举保存到 mongodb 时,它会保存 int 值 0、1 而不是 'LARGE'、'SMALL',关于如何保存字符串的任何想法?

【问题讨论】:

    标签: mongodb go protocol-buffers grpc


    【解决方案1】:

    Protobuf 用于通信,而不是用于数据库建模。你不应该使用 protobuf 生成的文件来保存在你的数据库中。

    而是创建一个单独的类型来模拟您要存储在数据库中的文档,您可以在其中存储枚举的字符串表示形式,并将其存储在数据库中。

    例如:

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

    并使用它:

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

    【讨论】:

    • 执行此操作的标准方法是什么,因为我确实看到 google 官方文档使用生成的代码进行建模,developers.google.com/protocol-buffers/docs/gotutorial
    • 另外,如果我创建单独的模型,例如,我有 2 个微服务,UserInventory,如果 Inventory 依赖于 User,这是否意味着我需要创建我自己的用户模型在InventoryUser 中都有两次?
    • 是的,它用于建模,但不是数据库对象,而是用于通信的数据。
    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多