good morning!!!!

Skip to content
Snippets Groups Projects
Commit 00a458bf authored by Carlos Nieto's avatar Carlos Nieto
Browse files

Adding example for mongo wrapper.

parent 0354d52a
No related branches found
No related tags found
No related merge requests found
......@@ -2,13 +2,19 @@ package main
import (
"fmt"
"time"
"upper.io/db"
_ "upper.io/db/mongo"
)
var settings = db.DataSource{
Host: "localhost",
Database: "dev",
var settings = db.Settings{
Database: `upperio_tests`,
Host: `127.0.0.1`,
}
type Birthday struct {
Name string `bson:"name"`
Born time.Time `bson:"born"`
}
func main() {
......@@ -16,47 +22,76 @@ func main() {
sess, err := db.Open("mongo", settings)
if err != nil {
panic(err)
fmt.Println("Unable to connect:", err.Error())
return
}
defer sess.Close()
animals, _ := sess.Collection("animals")
birthdayCollection, err := sess.Collection("birthdays")
if err != nil {
if err != db.ErrCollectionDoesNotExists {
fmt.Println("Could not use collection:", err.Error())
return
}
} else {
err = birthdayCollection.Truncate()
animals.Truncate()
if err != nil {
fmt.Println(err.Error())
return
}
}
animals.Append(db.Item{
"animal": "Bird",
"young": "Chick",
"female": "Hen",
"male": "Cock",
"group": "flock",
birthdayCollection.Append(Birthday{
Name: "Hayao Miyazaki",
Born: time.Date(1941, time.January, 5, 0, 0, 0, 0, time.UTC),
})
animals.Append(db.Item{
"animal": "Bovidae",
"young": "Calf",
"female": "Cow",
"male": "Bull",
"group": "Herd",
birthdayCollection.Append(Birthday{
Name: "Nobuo Uematsu",
Born: time.Date(1959, time.March, 21, 0, 0, 0, 0, time.UTC),
})
animals.Append(db.Item{
"animal": "Canidae",
"young": []string{"Puppy", "Pup"},
"female": "Bitch",
"male": "Dog",
"group": "Pack",
birthdayCollection.Append(Birthday{
Name: "Hironobu Sakaguchi",
Born: time.Date(1962, time.November, 25, 0, 0, 0, 0, time.UTC),
})
items, err := animals.FindAll()
var res db.Result
res, err = birthdayCollection.Filter()
if err != nil {
panic(err.Error())
}
for _, item := range items {
fmt.Printf("animal: %s, young: %s\n", item["animal"], item["young"])
var birthdays []Birthday
var birthday Birthday
// Pulling all at once.
err = res.All(&birthdays)
if err != nil {
panic(err.Error())
return
}
for _, birthday = range birthdays {
fmt.Printf("%s was born in %s.\n", birthday.Name, birthday.Born.Format("January 2, 2006"))
}
// Pulling one by one
for {
err = res.Next(&birthday)
if err == nil {
fmt.Printf("%s was born in %s.\n", birthday.Name, birthday.Born.Format("January 2, 2006"))
} else if err == db.ErrNoMoreRows {
break
} else {
panic(err.Error())
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment