From 6ee868e3ce8903f1b64132e076ee874136793028 Mon Sep 17 00:00:00 2001 From: Karina Date: Wed, 11 Mar 2020 18:51:24 -0600 Subject: [PATCH 1/2] Add InsertMany to mango --- mango.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/mango.go b/mango.go index 4eba515..2b6de0a 100644 --- a/mango.go +++ b/mango.go @@ -2,6 +2,7 @@ package mango import ( "context" + "errors" "reflect" "strings" @@ -146,3 +147,34 @@ func valueToBson(v reflect.Value) interface{} { } return bson.D{} } + +func InsertMany(values interface{}) (*mongo.InsertManyResult, error) { + array := reflectutils.DeepValue(reflect.ValueOf(values)) + if !isArray(array) || isEmptyArray(array) { + return nil, errors.New("invalid input value") + } + + document := getMongoDocument(array) + if document.Context == nil { + return nil, errors.New("invalid connection") + } + + collection := document.collection(values) + bsonArray := arrayToBsonA(array) + return collection.InsertMany(document.Context, bsonArray) + +} + +func isArray(v reflect.Value) bool { + return v.Kind() == reflect.Array || v.Kind() == reflect.Slice +} + +func isEmptyArray(v reflect.Value) bool { + return v.Len() == 0 +} + +func getMongoDocument(array reflect.Value) *Document { + firstItem := array.Index(0) + document := firstItem.FieldByName("Document") + return document.Addr().Interface().(*Document) +} From 4b30b3b823eb988b759ba037d910b97342161092 Mon Sep 17 00:00:00 2001 From: Karina Date: Wed, 11 Mar 2020 19:19:26 -0600 Subject: [PATCH 2/2] Create better error messages --- mango.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mango.go b/mango.go index 2b6de0a..671f159 100644 --- a/mango.go +++ b/mango.go @@ -151,12 +151,12 @@ func valueToBson(v reflect.Value) interface{} { func InsertMany(values interface{}) (*mongo.InsertManyResult, error) { array := reflectutils.DeepValue(reflect.ValueOf(values)) if !isArray(array) || isEmptyArray(array) { - return nil, errors.New("invalid input value") + return nil, errors.New("invalid input. Must be non empty array or slice") } document := getMongoDocument(array) if document.Context == nil { - return nil, errors.New("invalid connection") + return nil, errors.New("connection not registered in mongo document context") } collection := document.collection(values)