From ec41cbebcb230e1dcd9f4fd00874e7d8fafebb3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Carlos=20Nieto?= <jose.carlos@menteslibres.net> Date: Fri, 25 Apr 2014 11:00:19 -0500 Subject: [PATCH] The old Collection.UpsertId() trick to get the _id value of the latest inserted item stopped to work. This workaround allocates a new _id and then updates the item. --- mongo/collection.go | 12 +++++++----- mongo/database_test.go | 12 ++++++++++-- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/mongo/collection.go b/mongo/collection.go index f5acf569..f84ebcfd 100644 --- a/mongo/collection.go +++ b/mongo/collection.go @@ -196,17 +196,19 @@ func (self *Collection) Truncate() error { // Appends an item (map or struct) into the collection. func (self *Collection) Append(item interface{}) (interface{}, error) { + var err error var id bson.ObjectId - // Dirty trick to return the Id with ease. - res, err := self.collection.UpsertId(nil, item) + // Let's create an empty item to allocate an ID. + id = bson.NewObjectId() - if err != nil { + if err = self.collection.Insert(bson.M{"_id": id}); err != nil { return nil, err } - if res.UpsertedId != nil { - id = res.UpsertedId.(bson.ObjectId) + // Now append data the user wants to append. + if err = self.collection.Update(bson.M{"_id": id}, item); err != nil { + return nil, err } return id, nil diff --git a/mongo/database_test.go b/mongo/database_test.go index 4180bcbf..97b0af5b 100644 --- a/mongo/database_test.go +++ b/mongo/database_test.go @@ -39,8 +39,10 @@ import ( const wrapperName = "mongo" // Wrapper settings. -const host = "127.0.0.1" -const dbname = "upperio_tests" +const ( + host = "testserver.local" + dbname = "upperio_tests" +) // Global settings for tests. var settings = db.Settings{ @@ -91,6 +93,7 @@ func TestEnableDebug(t *testing.T) { } // Trying to open an empty datasource, it must succeed (mongo). +/* func TestOpenFailed(t *testing.T) { _, err := db.Open(wrapperName, db.Settings{}) @@ -98,6 +101,7 @@ func TestOpenFailed(t *testing.T) { t.Errorf(err.Error()) } } +*/ // Truncates all collections. func TestTruncate(t *testing.T) { @@ -175,6 +179,10 @@ func TestAppend(t *testing.T) { "name": "Ozzie", }) + if err != nil { + t.Fatalf("Append(): %s", err.Error()) + } + if id == nil { t.Fatalf("Expecting an ID.") } -- GitLab