I'm currently working on a project and right now I have some basic Javascript
blah.map(function(lBlah) {});
blah
is generated from an ajax request to a database which returns an array of objects (or slice if you prefer)
The only problem is I get a JS error: cannot read property 'map' of null
this is because if my one-to-many
association has no associated values at the time, it just makes that field nil
instead of an empty slice so when I json.Marshal
it it sends a null value instead of an empty []
which would fix all my errors, currently having to range over each struct
that is returned from the database and check for nil values then make([]blah, 0)
is annoying and looks messy. Is there an easier way to accomplish this? Is it possible to set a default json:"default:[]"
or something?
// ForumContainer is a table in the database
type ForumContainer struct {
gorm.Model
ContainerName string `sql:"not null;unique"`
AccessLevel int `sql:"not null;default:0"`
MainThreads []ForumMainThreads
}
// ForumMainThreads is the table in the database
type ForumMainThreads struct {
gorm.Model
ForumContainerID int `sql:"index"`
ThreadName string `sql:"not null;unique"`
Threads int `sql:"not null;default:0"`
Replies int `sql:"not null;default:0"`
AccessLevel int `sql:"not null;default:0"`
Posts []ForumMainThreadsPosts
}
// ForumMainThreadsPosts is a table in the database
type ForumMainThreadsPosts struct {
gorm.Model
UserID int `sql:"index"`
ForumMainThreadsID int `sql:"index"`
Title string `sql:"not null;unique"`
Body string `sql:"type:text;not null"`
Sticky bool `sql:"not null;default:0"`
Views int `sql:"not null;default:0"`
ReplyCount int `sql:"not null;default:0"`
Replies []ForumMainPostsReplies
}
// ForumMainPostsReplies is a table in the database
type ForumMainPostsReplies struct {
gorm.Model
ForumMainThreadsPostsID int `sql:"index"`
UserID int `sql:"index"`
Body string
}
Querying is accomplished by:
db.Preload("MainThreads").Find(&forumContainers)