From 7b2bdb46d2e8a8049b277128a62ce82fa7374e78 Mon Sep 17 00:00:00 2001 From: Bing-Yuan Hsieh Date: Wed, 20 Nov 2019 17:15:41 -0600 Subject: [PATCH] Added Patch method for the database. --- common/database/database.go | 1 + common/database/mongo_database.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/common/database/database.go b/common/database/database.go index e271ba0d..e46b24d5 100644 --- a/common/database/database.go +++ b/common/database/database.go @@ -14,6 +14,7 @@ type Database interface { Upsert(collection_name string, selector interface{}, update interface{}) (*ChangeResults, error) Update(collection_name string, selector interface{}, update interface{}) error UpdateAll(collection_name string, selector interface{}, update interface{}) (*ChangeResults, error) + Patch(collection_name string, selector interface{}, update *map[string]interface{}) error DropDatabase() error GetStats(collection_name string, fields []string) (map[string]interface{}, error) } diff --git a/common/database/mongo_database.go b/common/database/mongo_database.go index 82b6f553..2a6ce39f 100644 --- a/common/database/mongo_database.go +++ b/common/database/mongo_database.go @@ -7,6 +7,7 @@ import ( "github.com/HackIllinois/api/common/config" "gopkg.in/mgo.v2" + "gopkg.in/mgo.v2/bson" ) /* @@ -205,6 +206,20 @@ func (db *MongoDatabase) UpdateAll(collection_name string, selector interface{}, return &change_results, convertMgoError(err) } +/* + Finds an item based on the given selector and patches it with the data in update +*/ +func (db *MongoDatabase) Patch(collection_name string, selector interface{}, update *map[string]interface{}) error { + current_session := db.GetSession() + defer current_session.Close() + + collection := current_session.DB(db.name).C(collection_name) + + // Use mongodb set operator to update only the provided fields. + err := collection.Update(selector, bson.M{"$set": update}) + return convertMgoError(err) +} + /* Drops the entire database */