Replace populated fields with only the default field value
@param  {Object} doc
@param  {Object} fields
@return {Object}
193643
function(doc, fields) {
	return Object.keys(fields).reduce((prev, key) => {
		let val

		if (fields[key].hasOwnProperty('referenceCollection')) {
			const displayField = fields[key].referenceCollection.defaultField

			if (Array.isArray(doc[key])) {
				val = doc[key].map(data => {
					return data[displayField]
				})
			} else {
				val = doc[key][displayField]
			}
		} else {
			val = doc[key]
		}
		return Object.assign({}, prev, {
			[key]: val
		})
	}, { _id: doc._id })
}
341150
function (doc, ruleTree) {
    // Special case for "sets"
    if (_.isArray(doc))
      return _.map(doc, function (subdoc) { return transform(subdoc, ruleTree); });

    var res = details.including ? {} : EJSON.clone(doc);
    _.each(ruleTree, function (rule, key) {
      if (!_.has(doc, key))
        return;
      if (_.isObject(rule)) {
        // For sub-objects/subsets we branch
        if (_.isObject(doc[key]))
          res[key] = transform(doc[key], rule);
        // Otherwise we don't even touch this subfield
      } else if (details.including)
        res[key] = EJSON.clone(doc[key]);
      else
        delete res[key];
    });

    return res;
  }
684845
function load_field_defaults( $field )
	{
		if( !empty($this->defaults) )
		{
			foreach( $this->defaults as $k => $v )
			{
				if( !isset($field[ $k ]) )
				{
					$field[ $k ] = $v;
				}
			}
		}
		
		return $field;
	}
1218712
public static Field cloneField(Field field) {
    return new Field(field.name(), field.schema(), field.doc(),
        field.defaultValue());
  }
152957
def _populate(self, fields):
        
        schema = self.schema
        for k, v in fields.items():
            fields[k] = schema.fields[k].iget(self, v)

        self.modify(fields)
        self.reset_modified()
594487
private static Field[] removeMetaFields(Field[] fields) {
		Field[] realFields = new Field[fields.length - 1];
		//We'll delete at least one, sometimes more than one field (because there's at least the r$type field).
		int i = 0;
		for (Field field : fields) {
			if (!field.getName().startsWith(Constants.PREFIX)) {
				realFields[i++] = field;
			}
		}
		if (i < realFields.length) {
			realFields = Utils.arrayCopyOf(realFields, i);
		}
		if (GlobalConfiguration.assertsMode) {
			Utils.assertTrue(i == realFields.length, "Bug in removeMetaFields, created array of wrong length");
		}
		return realFields;
	}
597104
def fill_with_defaults(process_input, input_schema):
    """"""
    for field_schema, fields, path in iterate_schema(process_input, input_schema):
        if 'default' in field_schema and field_schema['name'] not in fields:
            dict_dot(process_input, path, field_schema['default'])
374234
function (fields) {
        return function(query, suggestions) {
            var tokens = text_util.splitTokens(text_util.split(query));
            var suggestionWords = [];

            if (suggestions.length === 1) {
                if (fields) {
                    collection_util.each(fields, function (stopwords, field) {
                        var fieldValue = object_util.getDeepValue(suggestions[0], field);
                        var fieldWords = fieldValue 
                            && text_util.splitTokens(text_util.split(fieldValue, stopwords));

                        if (fieldWords && fieldWords.length) {
                            suggestionWords = suggestionWords.concat(fieldWords);
                        }
                    });
                }

                if (collection_util.minusWithPartialMatching(tokens, suggestionWords).length === 0) {
                    return 0;
                }
            }

            return -1;
        }
    }
970785
function(theArray, doc) {
    if ( typeof common.fieldMatching(theArray, "id", doc.id) != ('undefined' || null)) {
        return common.fieldMatching(theArray, "id", doc.id); 
    }
    else {
        return null;
    };           
}
957460
function(doc){
    if(doc === null || typeof(doc) !== 'object'){
        return;
    }

    for(var key in doc){
        if(key[0] === '$'){
            throw new Error('Document fields can not start with "$"');
        }
        if(key.indexOf('.') !== -1){
            throw new Error('Document fields can not contain "."');
        }
        verifyDoc(doc[key]);
    }
}
1221793
function(fields){
    var sources = {};
    var toNames = {};
    var fromNames = {};
    var result = {
      defaultSource: false,
      fieldSource: {},
      toNames: toNames,
      fromNames: fromNames,
      sources: sources,
      __extend__: fieldsExtend
    };

    // default source is a source that defined for star rule
    if (fields['*'])
      result.defaultSource = fields['*'];

    // process fields from definition
    for (var field in fields)
    {
      var def = fields[field].split(':');
      var sourceName = def.shift();
      var sourceField = def.length ? def.join(':') : field;

      if (sourceName == result.defaultSource)
      {
        /** @cut */ if (field != '*')
        /** @cut */   basis.dev.warn('basis.data.object.Merge: source `' + sourceName + '` has already defined for any field (star rule), definition this source for `' + field + '` field is superfluous (ignored).');
        continue;
      }

      if (sourceName == '-' && sourceField != field)
      {
        /** @cut */ basis.dev.warn('basis.data.object.Merge: custom field name can\'t be used for own properties, definition `' + field + ': "' + fields[field] + '"` ignored.');
        continue;
      }

      if (!toNames[sourceName])
      {
        toNames[sourceName] = {};
        fromNames[sourceName] = {};
      }

      toNames[sourceName][field] = sourceField;
      fromNames[sourceName][sourceField] = field;
      result.fieldSource[field] = sourceName;
    }

    // generate source values getters
    for (var sourceName in toNames)
      sources[sourceName] = generateDataGetter(toNames[sourceName]);

    // generate values getter for default source
    if (result.defaultSource)
      sources[result.defaultSource] = function(data){
        var res = {};
        for (var key in data)
          if (key in result.fieldSource == false)
            res[key] = data[key];
        return res;
      };

    return result;
  }
341671
def _generate_field_with_default(**kwargs):
        """"""
        field = kwargs['field']
        if callable(field.default):
            return field.default()
        return field.default
862382
function getText(fieldBoost, doc) {
  var text;
  if (!fieldBoost.deepField) {
    text = doc[fieldBoost.field];
  } else { // "Enhance."
    text = doc;
    for (var i = 0, len = fieldBoost.deepField.length; i < len; i++) {
      if (Array.isArray(text)) {
        text = text.map(handleNestedObjectArrayItem(fieldBoost, fieldBoost.deepField.slice(i)));
      } else {
        text = text && text[fieldBoost.deepField[i]];
      }
    }
  }
  if (text) {
    if (Array.isArray(text)) {
      text = text.join(' ');
    } else if (typeof text !== 'string') {
      text = text.toString();
    }
  }
  return text;
}
983900
function fieldAssign(elem, field, val) {
        try {
            $(exports).triggerHandler('fieldAssign', [elem, field, val]);
        } catch (err) {
            console.error(err);
        }
        var isCustomField = (elem[field] && elem[field].__read);
        var oldVal;
        if (isCustomField) {
            oldVal = elem[field].__write();
        } else {
            oldVal = elem[field];
        }
        _currentOperation.ops.push({
            op: OP_FIELD_ASSIGN,
            arg: {
                _id: elem._id,
                f: field,
                n: val,
                o: oldVal
            }
        });
    }
37323
public static List<FieldInfo> processDefaultValue(List<Field> fields) {
        if (fields == null) {
            return null;
        }

        List<FieldInfo> ret = new ArrayList<FieldInfo>(fields.size());

        int maxOrder = 0;
        List<FieldInfo> unorderFields = new ArrayList<FieldInfo>(fields.size());
        for (Field field : fields) {
            Protobuf protobuf = field.getAnnotation(Protobuf.class);
            if (protobuf == null) {
                throw new RuntimeException("Field '" + field.getName() + "' has no @Protobuf annotation");
            }

            // check field is support for protocol buffer
            // any array except byte array is not support
            String simpleName = field.getType().getName();
            if (simpleName.startsWith("[")) {
                if ((!simpleName.equals(byte[].class.getName())) && (!simpleName.equals(Byte[].class.getName()))) {
                    throw new RuntimeException("Array type of field '" + field.getName() + "' on class '"
                            + field.getDeclaringClass().getName() + "' is not support,  please use List instead.");
                }
            }

            FieldInfo fieldInfo = new FieldInfo(field);
            fieldInfo.setRequired(protobuf.required());
            fieldInfo.setDescription(protobuf.description());

            // process type
            if (protobuf.fieldType() == FieldType.DEFAULT) {
                FieldType fieldType = TYPE_MAPPING.get(field.getType());
                if (fieldType == null) {
                    // check if type is enum
                    if (Enum.class.isAssignableFrom(field.getType())) {
                        fieldType = FieldType.ENUM;
                    } else {
                        fieldType = FieldType.OBJECT;
                    }
                }
                fieldInfo.setFieldType(fieldType);
            } else {
                fieldInfo.setFieldType(protobuf.fieldType());
            }

            int order = protobuf.order();
            if (order > 0) {
                fieldInfo.setOrder(order);
                if (order > maxOrder) {
                    maxOrder = order;
                }
            } else {
                unorderFields.add(fieldInfo);
            }

            ret.add(fieldInfo);
        }

        if (unorderFields.isEmpty()) {
            return ret;
        }

        for (FieldInfo fieldInfo : unorderFields) {
            maxOrder++;
            fieldInfo.setOrder(maxOrder);

            LOGGER.warning("Field '" + fieldInfo.getField().getName() + "' from "
                    + fieldInfo.getField().getDeclaringClass().getName()
                    + " with @Protobuf annotation but not set order or order is 0," + " It will set order value to "
                    + maxOrder);
        }

        return ret;
    }
29274
function modifyProperties(schema, paths) {
  if (!paths.length) { return; }

  const options = paths[0].options;

  /**
  * Modify document enum (string) properties to an object, with (original) value and
  * values (enumValues)
  *
  */
  function populatePropertyFor (documents, next) {
    if (this._mongooseOptions.lean) {
      asArray(documents).forEach(function(doc) {
        paths.forEach(function(path) {
          try {
            const splitted = path.path.split('.');
            const key      = splitted.shift();
            const insert   = { values: path.enumValues };
            const value    = doc[key];

            insert.value = determineValue(splitted, value);
            doc[key]     = nest(splitted, insert);
          } catch (error) { return next(error); }
        });
      });
    }

    next();
  }

  /**
  * If a document is modified, this method will locate the value on updates and assign it to the
  * appropriate property, allowing for proper validations later.
  * @param <Function>: next - function that notifies mongoose this middleware is complete
  */
  function reformatUpdateProperty(next) {
    const document = this._update['$set'];

    if (document) {
      paths.forEach(function(path) {
        try {
          const splitted = path.path.split('.');
          const key      = splitted.shift();

          if (document[key] === undefined) { return; }

          const value   = determineValue(splitted, document[key]);

          document[key] = nest(splitted, value);
        } catch (error) { return next(error); }
      });
    }

    next();
  }

  /**
  * If a document is modified, this method will locate the value before save/validation and assign it to the
  * appropriate property, allowing for proper validations later.
  * @param <Function>: next - function that notifies mongoose this middleware is complete
  */
  function reformatProperty(next) {
    const self = this;
    paths.forEach(function(path) {
      try {
        const splitted = path.path.split('.');
        const key      = splitted.shift();
        const value    = determineValue(splitted, self[key]);

        self[key]      = nest(splitted, value);
      } catch (error) { return next(error); }
    });

    next();
  }

  /**
  * Setup handlers for modifying properties -- ['find', 'findOne']
  */
  options.modify.on.forEach(function(on) {
    schema.post(on, populatePropertyFor);
  });

  schema.pre((options.validateBeforeSave ? 'validate' : 'save'), reformatProperty);

  /*
  * Setup handlers for updating documents (there may be more to consider)
  */
  ['update', 'findOneAndUpdate'].forEach(function(on) {
    schema.pre(on, reformatUpdateProperty);
  });
}
913502
function(doc) {
  if (doc.params) {
    _.each(doc.params, function(param) {
      replaceNewLines(param, 'description');
    });
  }

  // Replace new lines in the return and params descriptions.
  var returns = doc.returns;
  if (returns) {
    replaceNewLines(returns, 'description');
  }
}