...

Source file src/go.mongodb.org/mongo-driver/internal/bsonutil/bsonutil.go

Documentation: go.mongodb.org/mongo-driver/internal/bsonutil

     1  // Copyright (C) MongoDB, Inc. 2017-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package bsonutil
     8  
     9  import (
    10  	"fmt"
    11  
    12  	"go.mongodb.org/mongo-driver/bson"
    13  )
    14  
    15  // StringSliceFromRawValue decodes the provided BSON value into a []string. This function returns an error if the value
    16  // is not an array or any of the elements in the array are not strings. The name parameter is used to add context to
    17  // error messages.
    18  func StringSliceFromRawValue(name string, val bson.RawValue) ([]string, error) {
    19  	arr, ok := val.ArrayOK()
    20  	if !ok {
    21  		return nil, fmt.Errorf("expected '%s' to be an array but it's a BSON %s", name, val.Type)
    22  	}
    23  
    24  	arrayValues, err := arr.Values()
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	strs := make([]string, 0, len(arrayValues))
    30  	for _, arrayVal := range arrayValues {
    31  		str, ok := arrayVal.StringValueOK()
    32  		if !ok {
    33  			return nil, fmt.Errorf("expected '%s' to be an array of strings, but found a BSON %s", name, arrayVal.Type)
    34  		}
    35  		strs = append(strs, str)
    36  	}
    37  	return strs, nil
    38  }
    39  
    40  // RawToDocuments converts a bson.Raw that is internally an array of documents to []bson.Raw.
    41  func RawToDocuments(doc bson.Raw) []bson.Raw {
    42  	values, err := doc.Values()
    43  	if err != nil {
    44  		panic(fmt.Sprintf("error converting BSON document to values: %v", err))
    45  	}
    46  
    47  	out := make([]bson.Raw, len(values))
    48  	for i := range values {
    49  		out[i] = values[i].Document()
    50  	}
    51  
    52  	return out
    53  }
    54  
    55  // RawToInterfaces takes one or many bson.Raw documents and returns them as a []interface{}.
    56  func RawToInterfaces(docs ...bson.Raw) []interface{} {
    57  	out := make([]interface{}, len(docs))
    58  	for i := range docs {
    59  		out[i] = docs[i]
    60  	}
    61  	return out
    62  }
    63  

View as plain text