如何使用golang将字符串作为ISODate插入mongo数据库?

thtygnil  于 2023-02-01  发布在  Go
关注(0)|答案(1)|浏览(240)

我有以下事务结构

type Transaction struct {
    ID       primitive.ObjectID `json:"id" bson:"_id"`
    Category primitive.ObjectID `bson:"category,omitempty"`
    Amount   string             `json:"amount" binding:"required"`
    Owner    primitive.ObjectID `bson:"owner,omitempty"`
    Date     primitive.DateTime `bson:"date" json:"date"`
    //Date     time.Time          `bson:"date" json:"date"`
}
var transaction models.Transaction
if err := c.ShouldBindJSON(&transaction); err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    return
}
createdTransaction, createErr := handler.collection.InsertOne(handler.ctx, transaction)

我试图以Mon Jan 30 2023 17:27:16 GMT+0200 (Eastern European Standard Time)传递日期,但收到Bad Request错误消息。如何将ISODate的日期插入mongodb?

dffbzjpn

dffbzjpn1#

更改此行:
createdTransaction, createErr := handler.collection.InsertOne(handler.ctx, transaction)
要像这样包含&transaction作为最后一个参数InsertOne,它将引用要存储的数据,而不是一个值:
createdTransaction, createErr := handler.collection.InsertOne(handler.ctx, &transaction)

相关问题