V
V
Valeriy Solovyov2015-02-22 18:18:15
go
Valeriy Solovyov, 2015-02-22 18:18:15

How to avoid copy-paste when working with mongodb?

Hello everyone
In order to work with mongoy, I wrote a quick code (below).
Monga is supposed to store 100500 properties for objects. Objects - apartments, cars and so on.
I'm interested in the possibility to reduce the code. For example, when declaring a type, I have to declare 100500 properties:

type Car struct {
  Id          bson.ObjectId `bson:"_id"`
  Url         string        `bson:"url"`
  Description string        `bson:"descriprion"`
  Val        []CarProps    `bson:"CarProps"`

  Count int `bson:"count"`
}
type CarProps struct {
  CO2 string `bson:"CO2"`
        Fuel string `bson:"FUEL"`
}

PS:
Sample code for working with mongo.
func RunInsertQuery(document interface{}, mongoSession *mgo.Session, conn Conn) {
  sessionCopy := mongoSession.Copy()
  defer sessionCopy.Close()
  collection := sessionCopy.DB(conn.Database).C(conn.Collection)
  err := collection.Insert(document)
  if err != nil {
    log.Printf("RunQuery : ERROR : %s\n", err)
  }
}
func RunFindAllQuery(document interface{}, m bson.M, mongoSession *mgo.Session, conn Conn) (err error) {
  sessionCopy := mongoSession.Copy()
  defer sessionCopy.Close()
  collection := sessionCopy.DB(conn.Database).C(conn.Collection)

  err = collection.Find(m).All(document)
  fmt.Printf("%v\n", document)
  if err != nil {
    log.Printf("RunQuery : ERROR : %s\n", err)
  }
  return err
}
type Conn struct {
  Database   string
  Collection string
}

func main() {
conn := Conn{Database: Database, Collection: "test"}
  mongoDBDialInfo := &mgo.DialInfo{
    Addrs:    []string{MongoDBHosts},
    Timeout:  60 * time.Second,
    Database: conn.Database,
  }

  mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
  if err != nil {
    log.Fatalf("CreateSession: %s\n", err)
    os.Exit(1)
  }

  defer mongoSession.Close()
        var carobj Car
  carobj.Id = bson.NewObjectId()
  carobj.Description = "sddsd"
  carobj.Tags = []CarProps{CarProps{CO2: "a"}}
  RunInsertQuery(carobj, mongoSession, conn)
        m := bson.M{"descriprion": "sddsd"}
        var carobjFindAll []Car
  _ = RunFindAllQuery(&carobjFindAll, m, mongoSession, conn)
  for cur := range carobjFindAll {
    fmt.Printf("\nrult: %s\n", carobjFindAll[cur].Id)
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey K, 2015-02-22
@mututunus

This is the price paid for static typing. But on the other hand, it's good.

K
kolesnevg, 2015-03-02
@kolesnevg

You can do a feint with your ears for this - give up static typing, make the declaration structure similar to

type Item struct{
Fields map[string]string
}

and use strings for keys and values, this will make it easier to save an instance of an object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question