mongo object references in mongoose
Certainly! Here's an example of how you might create object references in MongoDB using Go and Mongoose:
- Define the Schemas:
``go type Author struct { ID primitive.ObjectID
bson:"_id,omitempty"Name string
bson:"name"Books []primitive.ObjectID
bson:"books,omitempty"` }
type Book struct {
ID primitive.ObjectID bson:"_id,omitempty"
Title string bson:"title"
Author primitive.ObjectID bson:"author,omitempty"
}
```
Create the References:
go author := Author{ Name: "J.K. Rowling", } book := Book{ Title: "Harry Potter and the Sorcerer's Stone", Author: author.ID, }
Save the Data: ```go // Save author _, err := collection.InsertOne(context.Background(), author) if err != nil { log.Fatal(err) }
// Save book _, err = collection.InsertOne(context.Background(), book) if err != nil { log.Fatal(err) } ```
- Fetch Data with References: ```go var fetchedBook Book err = collection.FindOne(context.Background(), bson.M{"title": "Harry Potter and the Sorcerer's Stone"}).Decode(&fetchedBook) if err != nil { log.Fatal(err) }
var fetchedAuthor Author err = collection.FindOne(context.Background(), bson.M{"_id": fetchedBook.Author}).Decode(&fetchedAuthor) if err != nil { log.Fatal(err) } ```
This example demonstrates the creation of object references between an Author
and a Book
using MongoDB in Go.