Skip to content

Commit

Permalink
feat: insertOne() now returns the document with its ID
Browse files Browse the repository at this point in the history
  • Loading branch information
miilord committed Jun 16, 2024
1 parent 0b72745 commit de957d6
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ go.work

# MacOS
.DS_Store
.vscode/launch.json
6 changes: 5 additions & 1 deletion crud.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"

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

Expand All @@ -12,10 +13,13 @@ import (
func (r *Repo[T]) InsertOne(ctx context.Context, doc T, opts ...*options.InsertOneOptions) (T, error) {
doc.BeforeInsert(ctx)
defer doc.AfterInsert(ctx)
_, err := r.collection.InsertOne(ctx, doc, opts...)
res, err := r.collection.InsertOne(ctx, doc, opts...)
if err != nil {
return *new(T), err
}
if id, ok := res.InsertedID.(primitive.ObjectID); ok {
doc.SetID(id)
}
return doc, nil
}

Expand Down
1 change: 1 addition & 0 deletions crud_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func TestRepo_InsertOne(t *testing.T) {
var doc TestUser
err = db.Collection(testColl).FindOne(ctx, bson.M{"age": 6}).Decode(&doc)
require.NoError(t, err)
require.NotNil(t, doc.ID)
require.NotNil(t, doc.CreatedAt)
require.NotNil(t, doc.UpdatedAt)
}
Expand Down
2 changes: 2 additions & 0 deletions document.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ package modm
import (
"context"

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

// Document represents an interface for common document operations.
type Document interface {
SetID(id primitive.ObjectID)
BeforeInsert(ctx context.Context)
AfterInsert(ctx context.Context)
BeforeUpdate(ctx context.Context)
Expand Down
4 changes: 4 additions & 0 deletions field.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ type DefaultField struct {
UpdatedAt time.Time `bson:"updated_at,omitempty" json:"updated_at"`
}

func (df *DefaultField) SetID(id primitive.ObjectID) {
df.ID = id
}

// DefaultUpdatedAt sets the default value for the UpdatedAt field.
func (df *DefaultField) DefaultUpdatedAt() {
df.UpdatedAt = time.Now()
Expand Down

0 comments on commit de957d6

Please sign in to comment.