Skip to content

Commit

Permalink
feat: add IsDocumentExists function
Browse files Browse the repository at this point in the history
  • Loading branch information
miilord committed Jan 11, 2024
1 parent a39e2a3 commit 8ca60eb
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
28 changes: 28 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,34 @@ func GetPointer[T any](value T) *T {
return &value
}

// IsDocumentExists checks if a MongoDB FindOne/Find operation returned an error indicating
// the absence of documents. It returns true if documents are found, false if
// no documents are found, and any other error encountered during the operation.
// The function is designed to be used in conjunction with MongoDB FindOne/Find queries.
// Example:
//
// _, err := db.Mongo.Account.FindOne(context.TODO(), filter)
// exists, err := IsDocumentExists(err)
// if err != nil {
// return err
// }
// if !exists {
// return fmt.Errorf("Document not found")
// }
func IsDocumentExists(err error) (bool, error) {
// if err == mongo.ErrNoDocuments {
// err = nil
// }
// return err == nil, err
if err == nil {
return true, nil
}
if err == mongo.ErrNoDocuments {
return false, nil
}
return false, err
}

// Generate index models from unique and compound index definitions.
// If uniques/indexes is []string{"name"}, means create index "name"
// If uniques/indexes is []string{"name,-age","uid"}, means create compound indexes: name and -age, then create one index: uid
Expand Down
31 changes: 31 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package modm

import (
"errors"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -17,6 +18,36 @@ func TestGetPointer(t *testing.T) {
assert.Equal(t, value, *ptr)
}

func TestIsDocumentExists(t *testing.T) {
// Case 1: Error is nil
exists, err := IsDocumentExists(nil)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
if !exists {
t.Error("Expected true, got false")
}

// Case 2: Error is mongo.ErrNoDocuments
exists, err = IsDocumentExists(mongo.ErrNoDocuments)
if err != nil {
t.Errorf("Expected nil error, got %v", err)
}
if exists {
t.Error("Expected false, got true")
}

// Case 3: Other error
otherError := errors.New("some other error")
exists, err = IsDocumentExists(otherError)
if err != otherError {
t.Errorf("Expected %v error, got %v", otherError, err)
}
if exists {
t.Error("Expected false, got true")
}
}

func TestIndexesToModel(t *testing.T) {
uniques := []string{"name", "uid"}
indexes := []string{"name,-age", "email"}
Expand Down

0 comments on commit 8ca60eb

Please sign in to comment.