Home > Net >  MongoDB does not save timestamps
MongoDB does not save timestamps

Time:12-01

I need to save the timestamps for createdAt and updatedAt properties in the database, but they are not being saved automatically, they are being saved as {T: 0, I: 0}. I am using Mongo Driver to perform CRUD operations.

So, this leds me to another problem while attaching the current time to the user model; I read somewhere that both createdAt and updatedAt have to be primitive.Timestamp, but I don't know how to really save them. I have tried User.CreatedAt = with:

  • time.Now()
  • new primitive.Timestamp(time.Now(), 1))
  • primitive.Timestamp{ T: uint32(time.Now().Unix()), I: 0 } (this seems to be working)

Getting back to the main problem, the best solution should be that the database allows me to configure the timestamps to be saved automatically whenever a insertOne() is triggered. That could work always that assigning primitive.Timestamp to User.CreatedAt is correct.

So, this is my model:

package models

import (
    "go.mongodb.org/mongo-driver/bson/primitive"
)

type User struct {
    Id           primitive.ObjectID  `bson:"_id,omitempty" json:"id,omitempty"`
    Email        string              `bson:"email" json:"email"`
    CreatedAt    primitive.Timestamp `bson:"createdAt" json:"createdAt"`
    UpdatedAt    primitive.Timestamp `bson:"updatedAt" json:"updatedAt"`
}

And this is my service:

func CreateUser(user models.User) (models.User, error) {
    db := database.GetDatabase()
    result, err := db.Collection(collection).InsertOne(context.TODO(), user)
    if err != nil {
        return models.User{}, err
    }

    user.Id = result.InsertedID.(primitive.ObjectID)
    user.CreatedAt = primitive.Timestamp{ T: uint32(time.Now().Unix()), I: 0 }
    return user, nil
}

So, it is ok to manage the timestamps like this or did I just mistaken?

CodePudding user response:

You can simply use time.Time:

type User struct {
    Id           primitive.ObjectID  `bson:"_id,omitempty" json:"id,omitempty"`
    Email        string              `bson:"email" json:"email"`
    CreatedAt    time.Time `bson:"createdAt" json:"createdAt"`
    UpdatedAt    time.Time `bson:"updatedAt" json:"updatedAt"`
}

MongoDB does not update these for you. You have to set them yourself before storing them in the DB:

user.CreatedAt=time.Now()
user.UpdatedAd=user.CreatedAt
result, err := db.Collection(collection).InsertOne(context.TODO(), user)
  • Related