0

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"`
}
Darien Miller
  • 651
  • 2
  • 7
  • 16
  • 1
    *"even though its value printed out before and after insertion in the Go console isn't nil"* -- `[]` can be `nil` and it can be an empty slice, see: https://go.dev/play/p/RSmPq36s3YY. – mkopriva Jun 23 '22 at 03:47

2 Answers2

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

ashing
  • 131
  • 3
0

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()))
Veslav
  • 11
  • 2