Mongodb时间序列 / Golang - ['timestamp'必须存在并包含有效的BSON UTC日期时间值]

4
我有以下示例 Go 代码,它从 REST 请求(GIN)中将数据插入到 MongoDB,但是它失败了:
['timestamp' must be present and contain a valid BSON UTC datetime value]

代码:

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"`
}

我做错了什么?我以为Mongodb会完成将time.time类型转换为MongoDB所需类型的整个过程。

是的,mongo-go驱动程序可以正确处理 time.Time值。请向我们展示您的devicesReadings值及其类型。 - icza
刚刚添加了类型。 - newduino
你调用了 InsertOne(),它可以用来插入单个文档。然而,devicesReadings 是多个文档的切片。 - icza
谢谢,搞定了。请发布解决方案,这样我就可以接受它作为答案。 - newduino
1个回答

0
你调用了Collection.InsertOne(),它可以用来插入单个文档。然而,devicesReadings 是一个包含多个文档的切片。
因此,你要么需要遍历所有文档并将它们逐个传递给 Collection.InsertOne(),要么使用 Collection.InsertMany(),传递希望插入的多个文档的切片。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接