rest-api/database/mongodb.go

59 lines
1.1 KiB
Go
Raw Permalink Normal View History

package database
import (
"github.com/Kamva/mgm/v3"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
// MongoDb type
type MongoDb struct {
database string
}
2020-09-29 22:35:59 +02:00
// New Connect to MongoDB Server
func New( /* dbName string */ ) *MongoDb {
dbName := "go-rest-api" // FIXME
mgm.SetDefaultConfig(nil, dbName, options.Client().ApplyURI("mongodb://user:passwd@localhost:27017"))
return &MongoDb{
database: dbName,
}
}
// FindByID func
func (m *MongoDb) FindByID(model mgm.Model, id string) error {
err := mgm.Coll(model).FindByID(id, model)
if err != nil {
return err
}
return nil
}
// FindAll func
func (m *MongoDb) FindAll(model mgm.Model, collection interface{}, filter bson.D) error {
err := mgm.Coll(model).SimpleFind(collection, filter)
if err != nil {
return err
}
return nil
}
// Create func
func (m *MongoDb) Create(model mgm.Model) error {
return mgm.Coll(model).Create(model)
}
// Update func
func (m *MongoDb) Update(model mgm.Model) error {
return mgm.Coll(model).Update(model)
}
// Remove func
func (m *MongoDb) Remove(model mgm.Model) error {
return mgm.Coll(model).Delete(model)
}