MCPcopy Index your code
hub / github.com/MongoEngine/mongoengine / to_mongo

Method to_mongo

mongoengine/base/document.py:332–386  ·  view source on GitHub ↗

Return as SON data ready for use with MongoDB.

(self, use_db_field=True, fields=None)

Source from the content-addressed store, hash-verified

330 return self._data["_text_score"]
331
332 def to_mongo(self, use_db_field=True, fields=None):
333 """
334 Return as SON data ready for use with MongoDB.
335 """
336 fields = fields or []
337
338 data = SON()
339 data["_id"] = None
340 data["_cls"] = self._class_name
341
342 # only root fields ['test1.a', 'test2'] => ['test1', 'test2']
343 root_fields = {f.split(".")[0] for f in fields}
344
345 for field_name in self:
346 if root_fields and field_name not in root_fields:
347 continue
348
349 value = self._data.get(field_name, None)
350 field = self._fields.get(field_name)
351
352 if field is None and self._dynamic:
353 field = self._dynamic_fields.get(field_name)
354
355 if value is not None:
356 f_inputs = field.to_mongo.__code__.co_varnames
357 ex_vars = {}
358 if fields and "fields" in f_inputs:
359 key = "%s." % field_name
360 embedded_fields = [
361 i.replace(key, "") for i in fields if i.startswith(key)
362 ]
363
364 ex_vars["fields"] = embedded_fields
365
366 if "use_db_field" in f_inputs:
367 ex_vars["use_db_field"] = use_db_field
368
369 value = field.to_mongo(value, **ex_vars)
370
371 # Handle self generating fields
372 if value is None and field._auto_gen:
373 value = field.generate()
374 self._data[field_name] = value
375
376 if value is not None or field.null:
377 if use_db_field:
378 data[field.db_field] = value
379 else:
380 data[field.name] = value
381
382 # Only add _cls if allow_inheritance is True
383 if not self._meta.get("allow_inheritance"):
384 data.pop("_cls")
385
386 return data
387
388 def validate(self, clean=True):
389 """Ensure that all fields' values are valid and that required fields

Callers 3

__getstate__Method · 0.95
to_jsonMethod · 0.95
_deltaMethod · 0.95

Calls 4

replaceMethod · 0.80
generateMethod · 0.80
popMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected