2
* Copyright (C) 2012 10gen Inc.
4
* This program is free software: you can redistribute it and/or modify
5
* it under the terms of the GNU Affero General Public License, version 3,
6
* as published by the Free Software Foundation.
8
* This program is distributed in the hope that it will be useful,
9
* but WITHOUT ANY WARRANTY; without even the implied warranty of
10
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
* GNU Affero General Public License for more details.
13
* You should have received a copy of the GNU Affero General Public License
14
* along with this program. If not, see <http://www.gnu.org/licenses/>.
17
#include "mongo/s/field_parser.h"
18
#include "mongo/util/mongoutils/str.h"
22
using mongoutils::str::stream;
24
// Extracts an array into a vector
26
FieldParser::FieldState FieldParser::extract(BSONObj doc,
27
const BSONField<vector<T> >& field,
31
BSONElement elem = doc[field.name()];
33
if (field.hasDefault()) {
34
*out = field.getDefault();
42
if (elem.type() == Array) {
43
BSONArray arr = BSONArray(elem.embeddedObject());
46
// Append all the new elements to the end of the vector
47
size_t initialSize = out->size();
48
out->resize(initialSize + arr.nFields());
51
BSONObjIterator objIt(arr);
52
while (objIt.more()) {
53
BSONElement next = objIt.next();
54
BSONField<T> fieldFor(next.fieldName(), out->at(initialSize + i));
56
if (!FieldParser::extract(arr,
58
&out->at(initialSize + i),
62
*errMsg = stream() << "error parsing element " << i << " of field "
63
<< field() << causedBy(elErrMsg);
74
*errMsg = stream() << "wrong type for '" << field() << "' field, expected "
75
<< "vector array" << ", found " << doc[field.name()].toString();
80
// Extracts an object into a map
81
template<typename K, typename T>
82
FieldParser::FieldState FieldParser::extract(BSONObj doc,
83
const BSONField<map<K, T> >& field,
87
BSONElement elem = doc[field.name()];
89
if (field.hasDefault()) {
90
*out = field.getDefault();
98
if (elem.type() == Object) {
99
BSONObj obj = elem.embeddedObject();
102
BSONObjIterator objIt(obj);
103
while (objIt.more()) {
104
BSONElement next = objIt.next();
105
T& value = (*out)[next.fieldName()];
107
BSONField<T> fieldFor(next.fieldName(), value);
108
if (!FieldParser::extract(obj, fieldFor, &value, &elErrMsg)) {
110
*errMsg = stream() << "error parsing map element " << next.fieldName()
111
<< " of field " << field() << causedBy(elErrMsg);
113
return FIELD_INVALID;
121
*errMsg = stream() << "wrong type for '" << field() << "' field, expected "
122
<< "vector array" << ", found " << doc[field.name()].toString();
124
return FIELD_INVALID;