arnaucube
arnaucube/goRecommenderPublic Self-hosted repository
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)
11
12//MongoConfig stores the configuration of mongodb to connect
13type MongoConfig struct {
14	Ip         string `json:"ip"`
15	Database   string `json:"database"`
16	Collection string `json:"collection"`
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) *mgo.Collection {
46
47	c := session.DB(mongoConfig.Database).C(mongoConfig.Collection)
48	return c
49}
50func connectMongodb() *mgo.Collection {
51	session, err := getSession()
52	if err != nil {
53		log.Fatal(err)
54	}
55	c := getCollection(session)
56	return c
57}
58
59func saveDataEntryToMongo(c *mgo.Collection, user UserModel) {
60	/*
61		how to call this function
62			var auxArr []string
63			user := UserModel{"123", auxArr}
64			saveDataEntryToMongo(c, user)
65	*/
66
67	err := c.Insert(user)
68	if err != nil {
69		log.Fatal(err)
70	}
71
72}