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 }