Skip to content

Commit 8ca60eb

Browse files
committed
feat: add IsDocumentExists function
1 parent a39e2a3 commit 8ca60eb

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

utils.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,34 @@ func GetPointer[T any](value T) *T {
1414
return &value
1515
}
1616

17+
// IsDocumentExists checks if a MongoDB FindOne/Find operation returned an error indicating
18+
// the absence of documents. It returns true if documents are found, false if
19+
// no documents are found, and any other error encountered during the operation.
20+
// The function is designed to be used in conjunction with MongoDB FindOne/Find queries.
21+
// Example:
22+
//
23+
// _, err := db.Mongo.Account.FindOne(context.TODO(), filter)
24+
// exists, err := IsDocumentExists(err)
25+
// if err != nil {
26+
// return err
27+
// }
28+
// if !exists {
29+
// return fmt.Errorf("Document not found")
30+
// }
31+
func IsDocumentExists(err error) (bool, error) {
32+
// if err == mongo.ErrNoDocuments {
33+
// err = nil
34+
// }
35+
// return err == nil, err
36+
if err == nil {
37+
return true, nil
38+
}
39+
if err == mongo.ErrNoDocuments {
40+
return false, nil
41+
}
42+
return false, err
43+
}
44+
1745
// Generate index models from unique and compound index definitions.
1846
// If uniques/indexes is []string{"name"}, means create index "name"
1947
// If uniques/indexes is []string{"name,-age","uid"}, means create compound indexes: name and -age, then create one index: uid

utils_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package modm
22

33
import (
4+
"errors"
45
"testing"
56

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

21+
func TestIsDocumentExists(t *testing.T) {
22+
// Case 1: Error is nil
23+
exists, err := IsDocumentExists(nil)
24+
if err != nil {
25+
t.Errorf("Expected nil error, got %v", err)
26+
}
27+
if !exists {
28+
t.Error("Expected true, got false")
29+
}
30+
31+
// Case 2: Error is mongo.ErrNoDocuments
32+
exists, err = IsDocumentExists(mongo.ErrNoDocuments)
33+
if err != nil {
34+
t.Errorf("Expected nil error, got %v", err)
35+
}
36+
if exists {
37+
t.Error("Expected false, got true")
38+
}
39+
40+
// Case 3: Other error
41+
otherError := errors.New("some other error")
42+
exists, err = IsDocumentExists(otherError)
43+
if err != otherError {
44+
t.Errorf("Expected %v error, got %v", otherError, err)
45+
}
46+
if exists {
47+
t.Error("Expected false, got true")
48+
}
49+
}
50+
2051
func TestIndexesToModel(t *testing.T) {
2152
uniques := []string{"name", "uid"}
2253
indexes := []string{"name,-age", "email"}

0 commit comments

Comments
 (0)