如何解决如何在Mongodb中将枚举存储为字符串而不是int
我正在使用 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 生成的文件保存在您的数据库中。
相反,创建一个单独的类型,对要存储在数据库中的文档进行建模,您可以在其中存储枚举的字符串表示形式,并将其存储在数据库中。
例如:
$("#registered").on('change',"input[type='checkbox']",function(){
var idx = array.indexOf($(this).val());
if ($(this).prop('checked')) {
if (array.indexOf($(this).val()) < 0) {
array.push($(this).val());
}
}else{
if (array.indexOf($(this).val()) >= 0) {
array.splice(array.indexOf($(this).val()),1);
}
}
});
并使用它:
type MyData {
Inventory string `bson:"inventory"`
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。