Work with schema validation in Golang

Hello,

I am trying to use schema validation on a specific collection of my database. Unfortunately, document insertion fails without any precision about what error has happened during the validation process.

Here’s the validator

bson.M{
    "bsonType": "object",
    "required": []string{"endpointID", "ip", "port", "lastHeartbeatDate"},
    "properties": bson.M{
        "endpointID": bson.M{
            "bsonType":    "double",
            "description": "the endpoint Hash",
        },
        "ip": bson.M{
            "bsonType":    "string",
            "description": "the endpoint IP address",
        },
        "port": bson.M{
            "bsonType":    "int",
            "maximum":     65535,
            "description": "the endpoint Port",
        },
        "lastHeartbeatDate": bson.M{
            "bsonType":    "date",
            "description": "the last time when the heartbeat has been received",
        },
    },
}

And here’s an attempt to insert a document

type GameServer struct {
    ID                primitive.ObjectID `bson:"_id,omitempty"`
    EndpointID        int64              `bson:"endpointID,omitempty"`
    IP                string             `bson:"ip,omitempty"`
    Port              int32              `bson:"port,omitempty"`
    LastHeartbeatDate time.Time          `bson:"lastHeartbeatDate,omitempty"`
}

[...]

gs := GameServer{
    EndpointID:        123456789,
    IP:                "192.168.2.16",
    Port:              27015,
    LastHeartbeatDate: time.Now(),
}

ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
res, err := gameServersCollection.InsertOne(ctx, gs)

Not sure what is the reason of the validation error, I think with the latest versions of the Golang driver, the struct time.Time is compatible with the BSON Date type. I have also indexed the EndpointID field (unique index) and the LastHeartbeatDate field (TTL index) but I don’t think they are related to the validation process anyway.

Thank you for pointing me in the right direction.

After some trials and errors, I just realized I was using a “double” BSON type instead of “long” to represents “int64” Golang type.

I will keep an eye on MongoDB’s issue tracker :
https://jira.mongodb.org/browse/SERVER-20547

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.