Rumah >pembangunan bahagian belakang >Golang >Bagaimana untuk Mengabaikan Nulls Apabila Membongkar Dokumen MongoDB dalam Go?
Mengabaikan Nulls Semasa Menyahmarshaling Dokumen MongoDB
Mongo-Go-Driver menyediakan beberapa pendekatan untuk mengabaikan null apabila menyahmarshaling dokumen MongoDB ke dalam struct Go.
1. Penyahkod Tersuai untuk Jenis Tertentu
2. Penyahkod Null-Aware "Jenis-Neutral"
Contoh Kod:
// Nullaware decoder for all types, setting null values to zero values type NullawareDecoder struct { DefDecoder bsoncodec.ValueDecoder ZeroValue reflect.Value } // Decodes null values to zero values, otherwise delegates to the default decoder func (nd *NullawareDecoder) DecodeValue(dctx bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { if vr.Type() == bsontype.Null { if !val.CanSet() { return errors.New("value not settable") } if err := vr.ReadNull(); err != nil { return err } val.Set(nd.ZeroValue) return nil } return nd.DefDecoder.DecodeValue(dctx, vr, val) } // Register NullawareDecoder for desired types rb := bson.NewRegistryBuilder() rb.RegisterDecoder(reflect.TypeOf(""), &NullawareDecoder{bson.DefaultRegistry.LookupDecoder(reflect.TypeOf("")), reflect.ValueOf("")}) // ... (register for other types as needed) // Use the registry within a ClientOptions instance clientOpts := options.Client(). ApplyURI("mongodb://localhost:27017/"). SetRegistry(rb.Build()) // Initialize MongoDB client with customized registry to ignore nulls client, err := mongo.Connect(ctx, clientOpts)
Atas ialah kandungan terperinci Bagaimana untuk Mengabaikan Nulls Apabila Membongkar Dokumen MongoDB dalam Go?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!