Skip to content

Commit e58efd8

Browse files
author
Amit
committed
added base model and repositories for modifying and reading data from db.
1 parent 1450678 commit e58efd8

File tree

8 files changed

+586
-3
lines changed

8 files changed

+586
-3
lines changed

Readme.md

Lines changed: 165 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# go-mongodb-client
1+
# go-mongodb-client
22

33
A simple utility Go package for connecting to MongoDB.
44
This package provides the following features:
@@ -9,13 +9,15 @@ This package provides the following features:
99

1010
---
1111

12-
## 📦 Installation
12+
# 📦 Installation
1313

1414
```bash
1515
go get github.com/amitjangid80/go-mongodb-client@latest
1616
```
1717

18-
## 📦 Usage
18+
# 📦 Usage
19+
20+
## 📦 Creating Mongodb Config
1921

2022
### You can add this in your main.go file or wherever you are setting up your db connection
2123

@@ -83,5 +85,165 @@ func CreateCollections(config *config.Config) {
8385
}
8486
}
8587
}
88+
```
89+
90+
## 📦 Usage of Base Model and Repository Functions
91+
92+
### 📦 Base DML Model
93+
### You can use this Base model in your own domain model which will by default come with below structure
94+
95+
```go
96+
package mongodb_domain
97+
98+
type BaseDmlModel interface {
99+
SetCreatedBy(by string)
100+
SetCreatedOn(on string)
101+
SetModifiedBy(by string)
102+
SetModifiedOn(on string)
103+
GetId() string
104+
SetId(id string)
105+
}
106+
107+
type DmlModel struct {
108+
Id string `json:"id,omitempty" bson:"_id,omitempty"`
109+
CreatedOn string `json:"createdOn,omitempty" bson:"createdOn,omitempty"`
110+
CreatedBy string `json:"createdBy" bson:"createdBy"`
111+
ModifiedOn string `json:"modifiedOn,omitempty" bson:"modifiedOn,omitempty"`
112+
ModifiedBy string `json:"modifiedBy" bson:"modifiedBy"`
113+
}
114+
115+
// Implement Auditable interface
116+
func (d *DmlModel) SetCreatedBy(by string) { d.CreatedBy = by }
117+
func (d *DmlModel) SetCreatedOn(on string) { d.CreatedOn = on }
118+
func (d *DmlModel) SetModifiedBy(by string) { d.ModifiedBy = by }
119+
func (d *DmlModel) SetModifiedOn(on string) { d.ModifiedOn = on }
120+
func (d *DmlModel) GetId() string { return d.Id }
121+
func (d *DmlModel) SetId(id string) { d.Id = id }
122+
```
123+
124+
### Example User Model or Domain
125+
126+
```go
127+
type User struct {
128+
FirstName string `json:"firstName" bson:"firstName"`
129+
LastName string `json:"lastName" bson:"lastName"`
130+
MobileNumber string `json:"mobileNo" bson:"mobileNo"`
131+
EmailId string `json:"emailId" bson:"emailId"`
132+
Username string `json:"username" bson:"username"`
133+
Password string `json:"password" bson:"password"`
134+
DmlModel `bson:",inline"` // Add the Base DML Model Here in your domain or model
135+
}
136+
```
137+
138+
## 📦 Repository Functions
139+
140+
### Create or Insert document in a collection
141+
142+
```go
143+
func RegisterUser(user *domain.User) {
144+
// This function returns the result or error
145+
result, err := base_repository.CreateRepository[*domain.User]().Create(
146+
user,
147+
"YOUR_DB_NAME",
148+
"YOUR_COLLECTION_NAME",
149+
"username", // Username who is creating this document to store in createdBy, modifiedBy
150+
)
151+
}
152+
```
153+
154+
### Update document in a collection
86155

156+
```go
157+
func UpdateUser(user *domain.User) {
158+
// This function returns the result or error
159+
result, err := base_repository.UpdateRepository[*domain.User]().Update(
160+
user, // Include id in user data to update the document
161+
"YOUR_DB_NAME",
162+
"YOUR_COLLECTION_NAME",
163+
"username", // Username who is creating this document to store in modifiedBy
164+
)
165+
}
166+
```
167+
168+
### Delete document from a collection
169+
170+
```go
171+
func DeleteUser(id string) {
172+
// This function returns the result or error
173+
result, err := base_repository.DeleteRepository[*domain.User]().Delete(
174+
id,
175+
"YOUR_DB_NAME",
176+
"YOUR_COLLECTION_NAME"
177+
)
178+
}
179+
```
180+
181+
### Get data by using Get By Filter Repository from a collection and db
182+
183+
```go
184+
func GetUser(username string, password string) []*domain.User {
185+
// create options for mongo db query to get the document or documents
186+
// You can refer mongodb documents for available options
187+
filterOptions := options.Find()
188+
189+
// filter for mongodb query to get the document or documents
190+
filter := bson.M{
191+
"username": username,
192+
"password": password,
193+
}
194+
195+
// This function will return the result or error
196+
results, err := base_repository.GetByFilterRepository[*domain.User]().GetByFilter(
197+
filter,
198+
filterOptions,
199+
"YOUR_DB_NAME",
200+
"YOUR_COLLECTION_NAME",
201+
)
202+
203+
if err != nil {
204+
results = make([]*domain.User, 0)
205+
log.Printf("Failed to get client from DB: %v", err)
206+
}
207+
208+
return results
209+
}
210+
```
211+
212+
### Get data by using Get All Repository from a collection and db
213+
214+
```go
215+
func GetUser() []*domain.User {
216+
// This function will return the result or error
217+
results, err := base_repository.GetAllRepository[*domain.User]().GetAll(
218+
"YOUR_DB_NAME",
219+
"YOUR_COLLECTION_NAME",
220+
)
221+
222+
if err != nil {
223+
results = make([]*domain.User, 0)
224+
log.Printf("Failed to get client from DB: %v", err)
225+
}
226+
227+
return results
228+
}
229+
```
230+
231+
### Get data by using Get By Id Repository from a collection and db
232+
233+
```go
234+
func GetUserById(id string) []*domain.User {
235+
// This function will return the result or error
236+
results, err := base_repository.GetByIdRepository[*domain.User]().GetById(
237+
id,
238+
"YOUR_DB_NAME",
239+
"YOUR_COLLECTION_NAME",
240+
)
241+
242+
if err != nil {
243+
results = make([]*domain.User, 0)
244+
log.Printf("Failed to get client from DB: %v", err)
245+
}
246+
247+
return results
248+
}
87249
```

mongodb_domain/base.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package mongodb_domain
2+
3+
type BaseDmlModel interface {
4+
SetCreatedBy(by string)
5+
SetCreatedOn(on string)
6+
SetModifiedBy(by string)
7+
SetModifiedOn(on string)
8+
GetId() string
9+
SetId(id string)
10+
}
11+
12+
type DmlModel struct {
13+
Id string `json:"id,omitempty" bson:"_id,omitempty"`
14+
CreatedOn string `json:"createdOn,omitempty" bson:"createdOn,omitempty"`
15+
CreatedBy string `json:"createdBy" bson:"createdBy"`
16+
ModifiedOn string `json:"modifiedOn,omitempty" bson:"modifiedOn,omitempty"`
17+
ModifiedBy string `json:"modifiedBy" bson:"modifiedBy"`
18+
}
19+
20+
// Implement Auditable interface
21+
func (d *DmlModel) SetCreatedBy(by string) { d.CreatedBy = by }
22+
func (d *DmlModel) SetCreatedOn(on string) { d.CreatedOn = on }
23+
func (d *DmlModel) SetModifiedBy(by string) { d.ModifiedBy = by }
24+
func (d *DmlModel) SetModifiedOn(on string) { d.ModifiedOn = on }
25+
func (d *DmlModel) GetId() string { return d.Id }
26+
func (d *DmlModel) SetId(id string) { d.Id = id }

mongodb_repositories/cmd/create.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package mongodb_repositories
2+
3+
import (
4+
"context"
5+
"log"
6+
"time"
7+
8+
"github.com/amitjangid80/go-mongodb-client/mongodb_client"
9+
"github.com/amitjangid80/go-mongodb-client/mongodb_domain"
10+
"go.mongodb.org/mongo-driver/bson/primitive"
11+
)
12+
13+
type ICreateRepository[T mongodb_domain.BaseDmlModel] interface {
14+
Create(data T, dbName string, collectionName string, username string) (*T, error)
15+
}
16+
17+
type CreateRepositoryImpl[T mongodb_domain.BaseDmlModel] struct{}
18+
19+
func CreateRepository[T mongodb_domain.BaseDmlModel]() ICreateRepository[T] {
20+
return &CreateRepositoryImpl[T]{}
21+
}
22+
23+
// Create implements ICreateRepository.
24+
func (g *CreateRepositoryImpl[T]) Create(data T, dbName string, collectionName string, username string) (*T, error) {
25+
bgCtx := context.Background()
26+
ctx, cancel := context.WithTimeout(bgCtx, 5*time.Second)
27+
defer cancel()
28+
29+
now := time.Now().UTC().Format(time.RFC3339)
30+
31+
data.SetCreatedBy(username)
32+
data.SetCreatedOn(now)
33+
data.SetModifiedBy(username)
34+
data.SetModifiedOn(now)
35+
36+
collection := mongodb_client.GetDb(dbName).Collection(collectionName)
37+
result, err := collection.InsertOne(ctx, data)
38+
39+
if err != nil {
40+
log.Printf("❌ [Create] Failed to insert data in collection '%s', error: %v", collectionName, err)
41+
return nil, err
42+
}
43+
44+
// Convert ObjectID to hex string and set in response
45+
if oid, ok := result.InsertedID.(primitive.ObjectID); ok {
46+
data.SetId(oid.Hex())
47+
}
48+
49+
return &data, nil
50+
}

mongodb_repositories/cmd/delete.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package mongodb_repositories
2+
3+
import (
4+
"context"
5+
"errors"
6+
"log"
7+
"time"
8+
9+
"github.com/amitjangid80/go-mongodb-client/mongodb_client"
10+
"github.com/amitjangid80/go-mongodb-client/mongodb_domain"
11+
"go.mongodb.org/mongo-driver/bson"
12+
"go.mongodb.org/mongo-driver/bson/primitive"
13+
"go.mongodb.org/mongo-driver/mongo"
14+
)
15+
16+
type IDeleteRepository[T mongodb_domain.BaseDmlModel] interface {
17+
Delete(id string, dbName string, collectionName string) (*T, error)
18+
}
19+
20+
type DeleteRepositoryImpl[T mongodb_domain.BaseDmlModel] struct{}
21+
22+
func DeleteRepository[T mongodb_domain.BaseDmlModel]() IDeleteRepository[T] {
23+
return &DeleteRepositoryImpl[T]{}
24+
}
25+
26+
func (r *DeleteRepositoryImpl[T]) Delete(id, dbName, collectionName string) (*T, error) {
27+
var deletedDoc T
28+
29+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
30+
defer cancel()
31+
32+
objectID, err := primitive.ObjectIDFromHex(id)
33+
34+
if err != nil {
35+
log.Printf("[Delete] Invalid id: %s", id)
36+
return nil, err
37+
}
38+
39+
filter := bson.M{"_id": objectID}
40+
41+
collection := mongodb_client.GetDb(dbName).Collection(collectionName)
42+
result := collection.FindOneAndDelete(ctx, filter)
43+
44+
if err := result.Err(); err != nil {
45+
if errors.Is(err, mongo.ErrNoDocuments) {
46+
log.Printf("❌ [Delete] No document found for ID: %s", id)
47+
return nil, err
48+
}
49+
50+
log.Printf("❌ [Delete] Error deleting document: %v", err)
51+
return nil, err
52+
}
53+
54+
if err := result.Decode(&deletedDoc); err != nil {
55+
log.Printf("❌ [Delete] Failed to decode deleted document: %v", err)
56+
return nil, err
57+
}
58+
59+
return &deletedDoc, nil
60+
}

0 commit comments

Comments
 (0)