Answer the question
In order to leave comments, you need to log in
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"`
}
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
This is the price paid for static typing. But on the other hand, it's good.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question