I have the following transaction struct
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)
I am trying to pass the date, in the following format Mon Jan 30 2023 17:27:16 GMT 0200 (Eastern European Standard Time)
, and I get the Bad Request error.
How can I insert the following date format as ISODate
into mongodb?
CodePudding user response:
Change this line:
createdTransaction, createErr := handler.collection.InsertOne(handler.ctx, transaction)
To include &transaction
like this as the final parameter InsertOne
takes a reference to the data to be stored, not a value:
createdTransaction, createErr := handler.collection.InsertOne(handler.ctx, &transaction)
CodePudding user response:
type Transaction struct {
ID primitive.ObjectID `json:"id" bson:"_id"`
Category primitive.ObjectID `bson:"category,omitempty" json:"category"`
Amount string `json:"amount" binding:"required"`
Owner primitive.ObjectID `bson:"owner,omitempty" json:"owner"`
InvDt primitive.DateTime `bson:"invdt,omitempty" json:"invdt,omitempty"`
Date string `json:"date" binding:"required"`
Cat []map[string]interface{} `json:"cat" bson:"cat"`
}
const shortForm = "2006-01-02"
dt, _ := time.Parse(shortForm, transaction.Date)
transaction.InvDt = primitive.NewDateTimeFromTime(dt)
As was mentioned before, i need to use parse time as string