goRecommender/mongodb.go
mongodb.goRaw
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io/ioutil"
7 "log"
8
9 mgo "gopkg.in/mgo.v2"
10 "gopkg.in/mgo.v2/bson"
11)
12
13//MongoConfig stores the configuration of mongodb to connect
14type MongoConfig struct {
15 Ip string `json:"ip"`
16 Database string `json:"database"`
17}
18
19var mongoConfig MongoConfig
20
21func readMongodbConfig(path string) {
22 file, e := ioutil.ReadFile(path)
23 if e != nil {
24 fmt.Println("error:", e)
25 }
26 content := string(file)
27 json.Unmarshal([]byte(content), &mongoConfig)
28}
29
30func getSession() (*mgo.Session, error) {
31 session, err := mgo.Dial("mongodb://" + mongoConfig.Ip)
32 if err != nil {
33 panic(err)
34 }
35 //defer session.Close()
36
37 // Optional. Switch the session to a monotonic behavior.
38 session.SetMode(mgo.Monotonic, true)
39
40 // Optional. Switch the session to a monotonic behavior.
41 session.SetMode(mgo.Monotonic, true)
42
43 return session, err
44}
45func getCollection(session *mgo.Session, collection string) *mgo.Collection {
46
47 c := session.DB(mongoConfig.Database).C(collection)
48 return c
49}
50
51func saveDataEntryToMongo(c *mgo.Collection, user UserModel) {
52 /*
53 how to call this function
54 var auxArr []string
55 user := UserModel{"123", auxArr}
56 saveDataEntryToMongo(c, user)
57 */
58
59 err := c.Insert(user)
60 if err != nil {
61 log.Fatal(err)
62 }
63
64}
65
66func saveItem(c *mgo.Collection, item ItemModel) {
67 //first, check if the item already exists
68 result := ItemModel{}
69 err := c.Find(bson.M{"id": item.ID}).One(&result)
70 if err != nil {
71 //item not found, so let's add a new entry
72 err = c.Insert(item)
73 check(err)
74 } else {
75 /*result.Data = append(result.Data, dataEntry)
76 err = c.Update(bson.M{"id": dataEntry.ContratoCOD}, result)
77 if err != nil {
78 log.Fatal(err)
79 }*/
80 }
81
82}
83
84func saveUser(c *mgo.Collection, user UserModel) {
85 //first, check if the item already exists
86 result := UserModel{}
87 err := c.Find(bson.M{"id": user.ID}).One(&result)
88 if err != nil {
89 //item not found, so let's add a new entry
90 err = c.Insert(user)
91 check(err)
92 } else {
93 /*result.Data = append(result.Data, dataEntry)
94 err = c.Update(bson.M{"id": dataEntry.ContratoCOD}, result)
95 if err != nil {
96 log.Fatal(err)
97 }*/
98 }
99
100}
101
102func getUserById(id string) (UserModel, error) {
103 result := UserModel{}
104 err := userCollection.Find(bson.M{"id": id}).One(&result)
105 if err != nil {
106 //user not exist
107 return result, err
108 } else {
109 //user exist
110 return result, err
111 }
112}
113func getAllItems() ([]ItemModel, error) {
114 result := []ItemModel{}
115 iter := itemCollection.Find(nil).Limit(100).Iter()
116 err := iter.All(&result)
117 if err != nil {
118 //user not exist
119 return result, err
120 } else {
121 //user exist
122 return result, err
123 }
124}