-
Notifications
You must be signed in to change notification settings - Fork 86
/
sample.go
48 lines (38 loc) · 887 Bytes
/
sample.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
// "log"
)
type Person struct {
Name string `bson:"name"`
Phone string `bson:"phone"`
}
var peopleC *mgo.Collection
func Insert(person *Person) {
if person.Name == "" || GetResult(person.Name) != "" {
panic("insert conflict")
}
// Insert Datas
err := peopleC.Insert(person)
if err != nil {
panic(err)
}
}
func List() []*Person {
query := peopleC.Find(nil).Select(bson.M{"_id": 0}).Sort("_id")
list := []*Person{}
err := query.All(&list)
if err != nil {
panic(err)
}
return list
}
func GetResult(name string) string {
result := &Person{}
err := peopleC.Find(bson.M{"name": name}).Select(bson.M{"_id": 0}).One(&result)
if err != nil && err != mgo.ErrNotFound {
panic(err)
}
return result.Name
}