wrap is an abstraction layer on top of mongodb 🍃 to make it feel like sorta like firestore 🔥
MIT License
Wrap enables the full MongoDB feature set without ever having to touch BSON or other weird libraries. Everything is structured in a way that BSON and MongoDB stay completly hidden.
go get github.com/lucacasonato/wrap
import "github.com/lucacasonato/wrap"
client, err := wrap.Connect("mongodb://localhost:27017", 5*time.Second)
if err != nil {
panic(err)
}
db := client.Database("production")
note: you are only getting a refrence to the database here. you are not actually creating it yet
users := db.Collection("users")
note: you are only getting a refrence to the collection here. you are not actually creating it yet
doc, err := users.Add(&User{
Name: "Luca Casonato",
Email: "[email protected]",
FavoriteNumbers: []int{5, 10, 15},
LastEdited: time.Now(),
})
if err != nil {
panic(err)
}
data, err := doc.Get()
if err != nil {
panic(err)
}
user := User{}
data.DataTo(&user)
fmt.Println(user.Name)
err = doc.Update(update.Set("email", "[email protected]"), true)
if err != nil {
panic(err)
}
err = users.CreateIndex(map[string]wrap.Index{
"name": wrap.TextIndex,
"email": wrap.AscendingIndex,
})
if err != nil {
panic(err)
}
iterator, err := users.
Where(filter.AND(
filter.TextSearch("luca"),
filter.Equal("email", "[email protected]"),
)).
DocumentIterator()
if err != nil {
panic(err)
}
defer iterator.Close()
for iterator.Next() {
user := User{}
err := iterator.DataTo(&user)
if err != nil {
panic(err)
}
fmt.Println(user)
}
iterator, err = users.All().
Modify(map[string]interface{}{
"email": expressions.Exclude,
}).
AddFields(map[string]interface{}{
"averagefavoritenumber": expressions.MathAvg(expressions.Value("favoritenumbers")),
}).
DocumentIterator()
if err != nil {
panic(err)
}
defer iterator.Close()
for iterator.Next() {
user := map[string]interface{}{}
err := iterator.DataTo(&user)
if err != nil {
panic(err)
}
fmt.Println(user)
}
err := users.Transaction(func(users *wrap.Collection) error {
now := time.Now()
err := users.Document(luca.ID).Update(true, update.Set("lastedited", now))
if err != nil {
return err
}
err = users.Document(jaap.ID).Update(true, update.Set("lastedited", now))
if err != nil {
return err
}
return nil
})
if err != nil {
err = nil
}
A full example can be found in the "example" folder.
to build start a mongo server on localhost:27017
run tests with go test
Copyright (c) 2019 Luca Casonato
This project is licenced under the MIT licence. More details in the LICENCE file.