I am looping through an array of strings to create an document with that property ONLY if it doesn't exist:
(dbi: my GORM database instance)
var postTags []models.Tag
for _, tagSlug := range tagsArray {
tag := models.Tag{
Slug: tagSlug,
}
err = dbi.Where("slug = ?", tagSlug).FirstOrCreate(&tag).Error
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "Internal Server Error",
})
}
postTags = append(postTags, tag)
}
And then Creating a post with those tags:
post := models.Post{
...,
Tags: postTags
}]
dbi.Create(&post)
Models:
type Post struct {
BaseModel
Title string `json:"title"`
MarkdownUploadURL string `json:"markdownUploadUrl"`
AuthorID string `json:"authorId"`
Tags []Tag `json:"tags" gorm:"many2many:posts_tags"`
}
type Tag struct {
BaseModel
Slug string `json:"slug"`
}
I tried: Changing dbi.FirstOrCreate()
for dbi.First()
and then checking if errors.Is(err, gorm.ErrRecordNotFound
But every time The function is called I get different Tags with different IDs, even if they already exist in the database...