From ad7c7f38afb94e20930a2161c9b93d6de7d73afe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=99=E2=97=A6=20The=20Tablet=20=E2=9D=80=20GamerGirla?= =?UTF-8?q?ndCo=20=E2=97=A6=E2=9D=A7?= Date: Thu, 27 Mar 2025 19:58:43 -0400 Subject: [PATCH] replace `ReplaceOne` with `UpdateOne` this keeps timestamps intact... --- document_internals.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/document_internals.go b/document_internals.go index ae6be4a..7dccc2d 100644 --- a/document_internals.go +++ b/document_internals.go @@ -2,6 +2,7 @@ package orm import ( "context" + "errors" "fmt" "github.com/fatih/structtag" "go.mongodb.org/mongo-driver/v2/bson" @@ -122,7 +123,7 @@ func doSave(c *mongo.Collection, isNew bool, opts *SaveOptions, arg interface{}) } var asHasId = vp.Interface().(HasID) var asModel = vp.Interface().(IDocument) - if isNew && opts.SetTimestamps { + if (isNew && reflect.ValueOf(asHasId.Id()).IsZero()) && opts.SetTimestamps { d.setCreated(now) } if opts.SetTimestamps { @@ -135,6 +136,7 @@ func doSave(c *mongo.Collection, isNew bool, opts *SaveOptions, arg interface{}) return err } } + if isNew { nid := getLastInColl(c.Name(), asHasId.Id()) pnid := incrementInterface(nid) @@ -148,9 +150,23 @@ func doSave(c *mongo.Collection, isNew bool, opts *SaveOptions, arg interface{}) _, err = c.InsertOne(context.TODO(), d.serializeToStore()) if err == nil { d.setExists(true) + } else { + _, err = c.UpdateOne(context.TODO(), bson.D{{Key: "_id", Value: d.(HasID).Id()}}, bson.M{ + "$set": d.serializeToStore(), + }) + //_, err = c.ReplaceOne(context.TO_DO(), bson.D{{Key: "_id", Value: d.(HasID).Id()}}, d.serializeToStore()) } } else { - _, err = c.ReplaceOne(context.TODO(), bson.D{{Key: "_id", Value: d.(HasID).Id()}}, d.serializeToStore()) + //_, err = c.ReplaceOne(context.TO_DO(), bson.D{{Key: "_id", Value: d.(HasID).Id()}}, d.serializeToStore()) + _, err = c.UpdateOne(context.TODO(), bson.D{{Key: "_id", Value: d.(HasID).Id()}}, bson.M{ + "$set": d.serializeToStore(), + }) + if errors.Is(err, mongo.ErrNoDocuments) { + _, err = c.InsertOne(context.TODO(), d.serializeToStore()) + if err == nil { + d.setExists(true) + } + } } return err }