Skip to content

Commit

Permalink
Merge pull request #6 from Microkubes/ISSUE-437
Browse files Browse the repository at this point in the history
adds search by multiple values functionality
  • Loading branch information
blazhovsky authored Mar 25, 2020
2 parents 845e0ca + 210f29f commit ed54215
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
21 changes: 21 additions & 0 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,27 @@ func stringToObjectID(object map[string]interface{}) error {
return nil
}

// sliceToObjectID converts _id key from slice of strings to slice of bson.ObjectId
func sliceToObjectID(object map[string]interface{}) error {
if id, ok := object["id"]; ok {
delete(object, "id")
ids := strings.Split(id.(string), ",")
bsonIds := []bson.ObjectId{}
for _, id := range ids {
if !bson.IsObjectIdHex(id) {
return ErrInvalidInput("id is a invalid hex representation of an ObjectId")
}

if reflect.TypeOf(id).String() != "bson.ObjectId" {
bsonIds = append(bsonIds, bson.ObjectIdHex(id))
}
}
object["_id"] = bsonIds
}

return nil
}

// IsConditionalCheckErr check if err is dynamoDB condition error
func IsConditionalCheckErr(err error) bool {
if ae, ok := err.(awserr.RequestFailure); ok {
Expand Down
31 changes: 29 additions & 2 deletions mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,17 @@ func (s *MongoSession) GetAll(filter Filter, resultsTypeHint interface{}, order
slicePointer.Elem().Set(results)

if !s.repoDef.IsCustomID() {
if err := stringToObjectID(filter); err != nil {
return nil, ErrInvalidInput(err)
if id, ok := filter["id"]; ok {
// check if id field contains values separated by comma
if ok := strings.Contains(id.(string), ","); ok {
if err := sliceToObjectID(filter); err != nil {
return nil, ErrInvalidInput(err)
}
} else {
if err := stringToObjectID(filter); err != nil {
return nil, ErrInvalidInput(err)
}
}
}
}

Expand Down Expand Up @@ -417,6 +426,24 @@ func toMongoFilter(filter Filter) (map[string]interface{}, error) {
}
return nil, fmt.Errorf("unknown filter specification - supported type is $pattern")
}
// if filter key contains multiple values to search by
if val, ok := value.(string); ok {
if values := strings.Split(val, ","); len(values) > 1 {
mgf[key] = bson.M{
"$in": values,
}
continue
}
}
// if filter _id contains multiple id to search by
if val, ok := value.([]bson.ObjectId); ok {
if len(val) > 1 {
mgf[key] = bson.M{
"$in": val,
}
continue
}
}
mgf[key] = value // copy over the key=>value pairs to do exact matching
}
return mgf, nil
Expand Down

0 comments on commit ed54215

Please sign in to comment.