I am using official MongoDb Driver for Golang. I have a field with timestamp type which I want to update from my Golang code.
This is my struct (lastUpdate field is the timestamp field):
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type MyStruct struct {
Id primitive.ObjectID `json:"id" bson:"_id,omitempty"`
Name string `json:"name"`
Alias string `json:"alias"`
Signed bool `json:"signed"`
Age int `json:"age"`
CreatedDate time.Time `json:"createdDaate"`
LastUpdate primitive.Timestamp `json:"lastUpdate"`
}
Then I pass this bson to update my data:
// logic to update data
docID, _ := primitive.ObjectIDFromHex("5de30185e4fabe4778f0ffdf")
UpdateMyData(c, bson.M{"createdDate": time.Now(), "lastUpdate": time.Now().UnixNano() }, bson.M{"_id": docID})
//update method
func UpdateMyData(client *mongo.Client, updatedData bson.M, filter bson.M) int64 {
collection := client.Database("*****").Collection("*****")
atualizacao := bson.D{ {Key: "$set", Value: updatedData} }
updatedResult, err := collection.UpdateOne(context.TODO(), filter, atualizacao)
if err != nil {
log.Fatal("Error on updating one Hero", err)
}
return updatedResult.ModifiedCount
}
The content of UpdateMyData method is fine cause it simply accepts bson and call UpdateOne method to update data into database and works for all different fields I have properly.
The problem is time.Now().UnixNane() returning int64 value, the above code does not throw an error, but it changes the "type" of lastUpdated to Int64 inside my MongoDb database for that specific row! So what is the correct way of passing data into timestamp field, without changing its type?