|
| 1 | +--- |
| 2 | +sidebar_position: 26 |
| 3 | +--- |
| 4 | + |
| 5 | +# Populate |
| 6 | + |
| 7 | +Populate is a method that allows you to retrieve related documents from other collections based on references defined in your schema. The retrieved documents are automatically embedded into the results of your query. |
| 8 | + |
| 9 | +This is particularly useful for fetching associated data without having to perform multiple queries manually as well as for reducing the number of queries made to the database. This uses `$lookup` under the hood, which is a MongoDB aggregation stage that allows you to join documents from different collections. |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +### Type definitions |
| 14 | + |
| 15 | +Population is a bit tricky to work with in Go due to its type system. Here we utilize the power of generics to define a flexible population structure that can work with any type of documents. |
| 16 | + |
| 17 | + |
| 18 | +```go |
| 19 | +type Kingdom struct { |
| 20 | + ID primitive.ObjectID `json:"_id" bson:"_id"` |
| 21 | + Name string `json:"name" bson:"name"` |
| 22 | + CreatedAt time.Time `json:"created_at" bson:"created_at"` |
| 23 | + UpdatedAt time.Time `json:"updated_at" bson:"updated_at"` |
| 24 | +} |
| 25 | + |
| 26 | +type Monster struct { |
| 27 | + ID primitive.ObjectID `json:"_id" bson:"_id"` |
| 28 | + Name string `json:"name" bson:"name"` |
| 29 | + Category string `json:"category,omitempty" bson:"category,omitempty"` |
| 30 | + CreatedAt time.Time `json:"created_at" bson:"created_at"` |
| 31 | + UpdatedAt time.Time `json:"updated_at" bson:"updated_at"` |
| 32 | +} |
| 33 | + |
| 34 | +type GenericBestiary[T any, Y any] struct { |
| 35 | + ID primitive.ObjectID `json:"_id" bson:"_id"` |
| 36 | + Monster T `json:"monster" bson:"monster"` |
| 37 | + Kingdom Y `json:"kingdom" bson:"kingdom"` |
| 38 | +} |
| 39 | + |
| 40 | +type Bestiary = GenericBestiary[any, any] |
| 41 | + |
| 42 | +type DetailedBestiary = GenericBestiary[Monster, Kingdom] |
| 43 | + |
| 44 | +type PartiallyDetailedBestiary = GenericBestiary[Monster, primitive.ObjectID] |
| 45 | + |
| 46 | +``` |
| 47 | + |
| 48 | +### Model definition |
| 49 | + |
| 50 | +```go |
| 51 | +BestiaryModel := elemental.NewModel[Bestiary]("Bestiary", elemental.NewSchema(map[string]elemental.Field{ |
| 52 | + "Monster": { |
| 53 | + Type: elemental.ObjectID, |
| 54 | + Ref: "Monster", |
| 55 | + }, |
| 56 | + "Kingdom": { |
| 57 | + Type: elemental.ObjectID, |
| 58 | + Ref: "Kingdom", |
| 59 | + }, |
| 60 | +})) |
| 61 | +``` |
| 62 | + |
| 63 | +In the example above, we define a `Bestiary` model with two fields, `Monster` and `Kingdom`, which are references to other Elemental models. You can also directly provide a `Collection` attribute into a field instead of using the `Ref` attribute, which is a bit faster to work with and also allows to use a different collection name than the one registered in the referenced model. |
| 64 | + |
| 65 | + |
| 66 | +### Querying with Populate |
| 67 | + |
| 68 | +To use the `Populate` method, you can chain it to your query. The `Populate` method accepts a list of fields to populate and you can use it in a variety of ways depending on your preference. |
| 69 | + |
| 70 | +There is no limitation on the number of fields you can populate, and it can be chained alongside other Elemental query methods. |
| 71 | + |
| 72 | +Note that with `Populate` we use the `ExecInto` method to retrieve the results into a custom type since the base type of the model is not sufficient to hold the populated data and may even fail to unmarshal the results correctly. |
| 73 | + |
| 74 | +```go |
| 75 | +var bestiaries []DetailedBestiary |
| 76 | + |
| 77 | +BestiaryModel.Find().Populate("Monster", "Kingdom").ExecInto(&bestiaries) |
| 78 | + |
| 79 | +// or |
| 80 | + |
| 81 | +BestiaryModel.Find().Populate("monster", "kingdom").ExecInto(&bestiaries) |
| 82 | + |
| 83 | +// or |
| 84 | + |
| 85 | +BestiaryModel.Find().Populate("Monster").Populate("Kingdom").ExecInto(&bestiaries) |
| 86 | + |
| 87 | +// or |
| 88 | + |
| 89 | +BestiaryModel.Find().Populate("monster").Populate("kingdom").ExecInto(&bestiaries) |
| 90 | + |
| 91 | +// or |
| 92 | + |
| 93 | +BestiaryModel.Find().Populate("monster kingdom").ExecInto(&bestiaries) |
| 94 | + |
| 95 | +// or |
| 96 | + |
| 97 | +BestiaryModel.Find().Populate([]string{"Monster", "Kingdom"}).ExecInto(&bestiaries) |
| 98 | + |
| 99 | +// or |
| 100 | + |
| 101 | +BestiaryModel.Find().Populate(primitive.M{ |
| 102 | + "path": "monster", |
| 103 | + "pipeline": []primitive.M{ |
| 104 | + {"$addFields": primitive.M{ |
| 105 | + "category": primitive.M{"$toLower": "$category"}, |
| 106 | + }}, |
| 107 | + }, |
| 108 | +}, "Kingdom").ExecInto(&bestiaries) |
| 109 | + |
| 110 | +// or |
| 111 | + |
| 112 | +BestiaryModel.Find().Populate(primitive.M{ |
| 113 | + "path": "monster", |
| 114 | + "select": primitive.M{ |
| 115 | + "name": 1, |
| 116 | + "category": 1, |
| 117 | + }, |
| 118 | +}).Populate("Kingdom").ExecInto(&bestiaries) |
| 119 | +``` |
| 120 | + |
| 121 | +#### You can even just populate one field if you want to: |
| 122 | + |
| 123 | +```go |
| 124 | +var bestiaries []PartiallyDetailedBestiary |
| 125 | + |
| 126 | +BestiaryModel.Find().Populate("Monster").ExecInto(&bestiaries) |
| 127 | +``` |
| 128 | + |
| 129 | +### Creating a new document with a referenced document |
| 130 | + |
| 131 | +When creating a new document with a reference to another document, you can directly pass the document as the value of the field. Elemental will automatically handle the reference and store the ObjectID of the referenced document. |
| 132 | + |
| 133 | +```go |
| 134 | +monster := MonsterModel.Create(Monster{ |
| 135 | + Name: "Griffin", |
| 136 | + Category: "Beast", |
| 137 | +}).Exec() |
| 138 | + |
| 139 | +kingdom := KingdomModel.Create(Kingdom{ |
| 140 | + Name: "Temeria", |
| 141 | +}).Exec() |
| 142 | + |
| 143 | +bestiary := BestiaryModel.Create(Bestiary{ |
| 144 | + Monster: monster, |
| 145 | + Kingdom: kingdom, |
| 146 | +}).ExecT() |
| 147 | + |
| 148 | +fmt.Println("Bestiary created with ID:", bestiary.ID.Hex()) |
| 149 | +``` |
0 commit comments