Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

Added Patch method for the database. #270

Open
wants to merge 2 commits into
base: staging
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions common/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
15 changes: 15 additions & 0 deletions common/database/mongo_database.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/HackIllinois/api/common/config"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)

/*
Expand Down Expand Up @@ -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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's not a lot of extra effort, it would be nice to have update be an interface{} to match the signature of the other database functions. Not a big deal if not.

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})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's my understanding that this will only merge top-level changes, not nested fields. If so, it might be worth noting this in the comment above.

ie

{
  "foo": {
    "bar1": 1,
  }
}

merged with

{
  "foo": {
    "bar2": 2,
  }
}

results in

{
  "foo": {
    "bar2": 2,
  }
}

return convertMgoError(err)
}

/*
Drops the entire database
*/
Expand Down