0

I would like to ask you if there is a way to find out if insertion was successful when inserting new object using collection.

Insert(object) with single operation.

What I mean is that, I don't want to send another query to the db to find out if there is a record or not. I need one single atomic operation (insert -> result (isSuccessful) - pseudo code).

John Weldon
  • 39,849
  • 11
  • 94
  • 127
Tek
  • 1,178
  • 1
  • 12
  • 22

1 Answers1

1

The Insert method returns an error object that represents it success or failure. You need to set the safe mode of the session first to enable this behaviour.

session.SetSafe(&mgo.Safe{}) // <-- first set safe mode!
c := session.DB("test").C("people")
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"})
if err != nil { // <-- then check error after insert!
    fmt.Printf("There was an error: %v", err)
} else {
    fmt.Print("Success!")
}
pjvds
  • 938
  • 6
  • 11