skip to Main Content

So I have ran into some unexpected behavior when inserting a model into mongoDB. When I send an empty body via Postman to my server and insert it into my database, the returned result to Postman had name and number default to their expected default values, 0 and "", but for data, instead of defaulting to an empty array, it defaulted to null instead, even though its value printed out before and after insertion in the Go console isn’t nil, but an empty array. Assigning the data field an empty []int{} before insertion solves the issue, and so does manually sending an empty array as the data field from Postman, but I was curious if there was any other way to guarantee that array fields default to [] and not null when getting inserted.

Here is my model:

type Test struct{
    Name string `json:"name"   bson:"name"`
    Number int  `json:"number" bson:"number"`
    Data []int  `json:"data"   bson:"data"`
}

2

Answers


  1. Implement bson.Marshaler, and your MarshalBSON() function will be called when you save values

    package main
    
    import (
        "log"
    
        "go.mongodb.org/mongo-driver/bson"
    )
    
    type Test struct {
        Data []int `json:"data" bson:"data"`
    }
    
    func (t *Test) MarshalBSON() ([]byte, error) {
        if t.Data == nil {
            log.Println("t.Data is nil")
            t.Data = make([]int, 0)
        }
    
        type my Test
        return bson.Marshal((*my)(t))
    }
    
    func main() {
        h := Test{}
        data, _ := bson.Marshal(&h)
        log.Print(bson.Raw(data))
    }
    
    // output: 
    // 2009/11/10 23:00:00 t.Data is nil
    // 2009/11/10 23:00:00 {"data": []}
    
    

    demo go playground link: https://go.dev/play/p/1WlO_44hnco

    also, you can check this link: Autofill created_at and updated_at in golang struct while pushing into mongodb

    Login or Signup to reply.
  2. You can define a registry for your collection (or database) using mgocompat package.

    import "go.mongodb.org/mongo-driver/bson/mgocompat"
    
    ...........
        
    db := client.Database(dbName, options.Database().SetRegistry(mgocompat.NewRegistryBuilder().Build()))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search