mongodb schema with enums and common fields
By admin | 8 months ago
In MongoDB, schemas are not enforced in the database level as they are in relational databases. However, when using MongoDB with Go, you often define your data structures (schemas) in your Go code, typically using structs. This helps in mapping your application data to MongoDB documents.
Below is an example of how you might define various common data types and an enum in Go for use with MongoDB. For this example, let's assume we're creating a model for a user in a typical application:
package main import ( "go.mongodb.org/mongo-driver/bson/primitive" "time" ) type Gender string const ( Male Gender = "male" Female Gender = "female" Other Gender = "other" ) type User struct { ID primitive.ObjectID \`bson:"_id,omitempty"\` // MongoDB's unique identifier Username string \`bson:"username"\` // String type PasswordHash string \`bson:"password_hash"\` // String type for storing password hashes Email string \`bson:"email"\` // String type Age int \`bson:"age"\` // Integer type BirthDate time.Time \`bson:"birth_date"\` // Date type IsActive bool \`bson:"is_active"\` // Boolean type Gender Gender \`bson:"gender"\` // Enum type (using a custom type) Tags []string \`bson:"tags,omitempty"\` // Array of strings Settings map[string]string \`bson:"settings"\` // Map (or dictionary) type CreatedAt time.Time \`bson:"created_at"\` // Date type for storing creation time UpdatedAt time.Time \`bson:"updated_at"\` // Date type for storing the last update time } func main() { // User struct can be used here }
Explanation:
-
**ID**: Uses `primitive.ObjectID` from the MongoDB Go driver, which is the MongoDB-specific unique identifier for documents.
-
**Username, PasswordHash, Email**: These are simple string types.
-
**Age**: An integer to represent the age.
-
**BirthDate**: `time.Time` is used for date fields.
-
**IsActive**: A boolean to represent a state (active or not).
-
**Gender**: Here, we've defined a custom type `Gender` and set it as a string type with predefined constants to enforce an enum-like behavior.
-
**Tags**: A slice of strings (
[]string
) to represent a list of tags. -
**Settings**: A map with string keys and values to store user settings or preferences.
-
**CreatedAt, UpdatedAt**: Use `time.Time` to track creation and update timestamps.
This struct serves as a schema definition for your Go application and can be used with MongoDB drivers to interact with the database. The tags (e.g., bson:"username"
) specify how each field should be named in the MongoDB documents, ensuring the Go struct fields are correctly mapped to the corresponding MongoDB document fields.