Search code examples
mongodbgotime-seriesmongo-go

Mongodb Timeseries / Golang - ['timestamp' must be present and contain a valid BSON UTC datetime value]


I have the following example Go code that inserts data into MongoDB coming from a REST request (GIN), but it fails with:

['timestamp' must be present and contain a valid BSON UTC datetime value]

code:

func CreateDevicesReadings(c *gin.Context) {

var devicesReadings DevicesReadings
c.BindJSON(&devicesReadings)

// Connect to MongoDB
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
    c.JSON(500, gin.H{
        "message": "Internal Server Error. Could not connect to the database.",

    })
    log.Default().Println(err)
}

collection := client.Database("florly").Collection("devicesReadings")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)


// Set timestamp to the current time at the moment of the request
for i := 0; i < len(devicesReadings.DevicesReadings); i++ {
    devicesReadings.DevicesReadings[i].Timestamp = time.Now().UTC()
} 
_, err = collection.InsertOne(ctx, devicesReadings)
if err != nil {
    c.JSON(500, gin.H{
        "message": "Internal Server Error. Could not insert the data into the database.",
    })
    log.Default().Println(err)
} else {
    log.Default().Println("Data inserted successfully.")
}

client.Disconnect(context.Background())
}

type DeviceReadings struct {
    ID      primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
    Alias          string `json:"alias" bson:"alias"`
    Timestamp   time.Time `json:"timestamp,omitempty" bson:"timestamp"`
    SystemReadings SystemReadings `json:"systemReadings" bson:"systemReadings"`
    SensorReadings SensorReadings `json:"sensorsReadings" bson:"sensorsReadings"`
}

What I'm doing wrong? I thought that Mongodb does the whole process of converting type time.time to the type MongoDB looks for.


Solution

  • You call Collection.InsertOne(), which can be used to insert a single document. Yet, devicesReadings is a slice of multiple documents.

    So you either have to iterate over all documents and pass those individually to Collection.InsertOne(), or use Collection.InsertMany(), using a slice of multiple documents you want to insert.