Macros
macro to(b: untyped; t: typed): untyped
-
Macro to is automatic conversion from symbol/variable BsonDocument to specified Type. This doesn't support dynamic values of array, only support homogeneous value-type array. It can convert only when the field is exported or using special pragma bsonExport to enable its conversion without exporting the field itself to other modules.
For custom type conversion, user can provide the proc, func or converter named with pattern of "of" & Type.name. For example, the Type is SimpleObj so the proc name is ofSimpleObj. The complete example is shown below:
import anonimongo/core/bson type Embedtion = object embedfield*: int embedstat*: string wasProcInvoked: bool SimpleEmbedObject = object intfield*: int strfield*: string embed*: Embedtion proc ofEmbedtion(b: BsonBase): Embedtion = let embed = b.ofEmbed result.embedfield = embed["embedfield"] result.embedstat = embed["embedstat"] result.wasProcInvoked = true let bsimple = bson({ intfield: 42, strfield: "that's 42", embed: { embedfield: 42, embedstat: "42", }, }) let simple = bsimple.to SimpleEmbedObject doAssert simple.intfield == 42 doAssert simple.strfield == "that's 42" doAssert simple.embed.embedfield == 42 doAssert simple.embed.embedstat == "42" doAssert simple.embed.wasProcInvoked
Note that the ofType isn't checked for the outer most of Type because if user wants implement the specifics conversion, the user just can simply call it immediately without resorting to macro to.
Source Edit