如何在 Mongodb 中将枚举存储为字符串而不是 int
How to store enum as string instead of int in Mongodb
我正在使用 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',关于如何保存字符串的任何想法相反?
Protobuf 用于通信,不用于数据库建模。你不应该使用 protobuf 生成的文件来保存在你的数据库中。
而是创建一个单独的类型来模拟您要存储在数据库中的文档,您可以在其中存储枚举的字符串表示形式,并将存储在数据库中。
例如:
type MyData {
Inventory string `bson:"inventory"`
}
并使用它:
data := MyData{
Inventory: inventory.GetInventory().String(),
}
我正在使用 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',关于如何保存字符串的任何想法相反?
Protobuf 用于通信,不用于数据库建模。你不应该使用 protobuf 生成的文件来保存在你的数据库中。
而是创建一个单独的类型来模拟您要存储在数据库中的文档,您可以在其中存储枚举的字符串表示形式,并将存储在数据库中。
例如:
type MyData {
Inventory string `bson:"inventory"`
}
并使用它:
data := MyData{
Inventory: inventory.GetInventory().String(),
}