SHARE
TWEET

Untitled

a guest Apr 2nd, 2019 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package models
  2.  
  3. import (
  4.     "log"
  5.     "github.com/globalsign/mgo"
  6. )
  7.  
  8. const (
  9.     host = "127.0.0.1:27017"
  10.     source = "admin"
  11.     user = "user"
  12.     pass = "1234"
  13. )
  14.  
  15. var globalS *mgo.Session
  16.  
  17. func init() {
  18.     dialInfo := &mgo.DialInfo{
  19.         Addrs: []string{host},
  20.         Source: source,
  21.         Username: user,
  22.         Password: pass,
  23.     }
  24.  
  25.     s, err := mgo.DialWithInfo(dialInfo)
  26.     if err != nil {
  27.         log.Fatalln("create session error", err)
  28.     }
  29.     globalS = s
  30. }
  31.  
  32. func connect(db, collection string) (*mgo.Session, *mgo.Collection) {
  33.     s := globalS.Copy()
  34.     c := s.DB(db).C(collection)
  35.     return s, c
  36. }
  37.  
  38. func Insert(db, collection string, docs ...interface{}) error {
  39.     ms, c := connect(db, collection)
  40.     defer ms.Close()
  41.     return c.Insert(docs...)
  42. }
  43.  
  44. func FindOne(db, collection string, query, selector, result interface{}) error {
  45.     ms, c := connect(db, collection)
  46.     defer ms.Close()
  47.     return c.Find(query).Select(selector).One(result)
  48. }
  49.  
  50. func FindAll(db, collection string, query, selector, result interface{}) error {
  51.     ms, c := connect(db, collection)
  52.     defer ms.Close()
  53.     return c.Find(query).Select(selector).All(result)
  54. }
  55.  
  56. func Update(db, collection string, query, update interface{}) error {
  57.     ms, c := connect(db, collection)
  58.     defer ms.Close()
  59.     return c.Update(query, update)
  60. }
  61.  
  62. func Remove(db, collection string, query interface{}) error {
  63.     ms, c := connect(db, collection)
  64.     defer ms.Close()
  65.     return c.Remove(query)
  66. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top