Why does mgo not return the ID of inserted document?

Viewed 14628

According to the documentation (http://godoc.org/launchpad.net/mgo/v2) you can obtain the ID of your "Upserted" document if you use the Upsert method.

There is also an Insert method that does not provide this functionality.
Why is that? What if I want to perform an Insert instead of an Upsert? (or wouldn't ever be any valid reason to want to do that? I'm starting to wonder.)

3 Answers

You can always try the Upsert function to get the generated ID.

db := service.ConnectDb()
sessionCopy := db.Copy()
defer sessionCopy.Close() // clean up

collection := sessionCopy.DB(service.MongoDB.DTB).C(MessageCol.tbl)

log.Println("before to write: ", msg)

// Update record inserts and creates an ID if wasn't set (Returns created record with new Id)
info, err := collection.Upsert(nil, msg)
if err != nil {
    log.Println("Error write message upsert collection: ", err)
    return MessageMgo{}, err
}

if info.UpsertedId != nil {
    msg.Id = info.UpsertedId.(bson.ObjectId)
}

// gets room from mongo
room, err := GetRoom(msg.Rid)
if err != nil {
    return msg, err
}

// increments the msgcount and update it
room.MsgCount = room.MsgCount + 1
err = UpdateRoom(room)
if err != nil {
    return msg, err
}

return msg, err

This is a sample code I have and works fine.....

Related