我有以下示例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查找的类型的整个过程.

推荐答案

您可以调用Collection.InsertOne(),它可用于插入单个文档.然而,devicesReadings只是多个文档的一小部分.

因此,您要么迭代所有文档并将它们逐个传递给Collection.InsertOne(),要么使用Collection.InsertMany(),使用要插入的多个文档的切片.

Mongodb相关问答推荐

Tableau 与 Mongo DB Atlas by MongoDB 的连接缓存问题

Mongo按最大分组排序

Mongoose 聚合和多级组

如何向所有文档添加一个字段,其中前 100 个文档的值为 1,接下来的 100 个文档的值为 2,依此类推?

在推入 mongodb 时自动填充 golang struct 中的 created_at 和 updated_at

如何使用 Spring Data MongoDB 通过 GridFS ObjectId 获取二进制流

在 Ubuntu 14.04 中安装 MongoDB 失败

Mongo DB中的Upserting和Id问题

如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId

MongoDB:多个 $elemMatch

MongoDB:自动生成的 ID 为零

MongoDB + Node JS + 基于角色的访问控制 (RBAC)

没有数组的嵌入文档?

mongodb: UnknownError assertion src/mongo/db/server_options_helpers.cpp:355

RoboMongo:不显示所有文档

使用 $in 进行不区分大小写的搜索

从 nodejs 到 mongodb 或 mongoose 的动态数据库连接

带有 either or查询的mongoose findOne

按 id 删除记录?

为什么 Mongo 提示会使查询运行速度提高 10 倍?