For storage, store as JSON rather than BSON
This commit is contained in:
@@ -3,7 +3,6 @@ package entity
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
@@ -62,6 +61,18 @@ func (o One) Generic() bson.M {
|
||||
return m
|
||||
}
|
||||
|
||||
func (o One) MarshalJSON() ([]byte, error) {
|
||||
b, err := o.MarshalBSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := bson.M{}
|
||||
if err := bson.Unmarshal(b, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(v)
|
||||
}
|
||||
|
||||
func (o One) MarshalBSON() ([]byte, error) {
|
||||
isMin := fmt.Sprint(o) == fmt.Sprint(o.Query())
|
||||
if !isMin {
|
||||
@@ -73,19 +84,39 @@ func (o One) MarshalBSON() ([]byte, error) {
|
||||
if o.Attachments == nil {
|
||||
o.Attachments = make(map[string]Attachment)
|
||||
}
|
||||
b, err := json.Marshal(o)
|
||||
var v interface{}
|
||||
b, err := o.toBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := bson.M{}
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
if err := fromBytes(b, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range m {
|
||||
switch v.(type) {
|
||||
case string:
|
||||
m[k] = strings.TrimSpace(v.(string))
|
||||
}
|
||||
}
|
||||
return bson.Marshal(m)
|
||||
return bson.Marshal(v)
|
||||
}
|
||||
|
||||
func (o One) toBytes() ([]byte, error) {
|
||||
return json.Marshal(struct {
|
||||
ID string `bson:"_id,omitempty" json:"_id"`
|
||||
Name string `bson:"name,omitempty" json:"name"`
|
||||
Type string `bson:"type,omitempty" json:"type"`
|
||||
Title string `bson:"title,omitempty" json:"title"`
|
||||
Text string `bson:"text,omitempty" json:"text"`
|
||||
Modified int64 `bson:"modified,omitempty" json:"modified"`
|
||||
Connections map[string]Connection `bson:"connections" json:"connections"`
|
||||
Attachments map[string]Attachment `bson:"attachments" json:"attachments"`
|
||||
}{
|
||||
ID: o.ID,
|
||||
Name: o.Name,
|
||||
Type: o.Type,
|
||||
Title: o.Title,
|
||||
Text: o.Text,
|
||||
Modified: o.Modified,
|
||||
Connections: o.Connections,
|
||||
Attachments: o.Attachments,
|
||||
})
|
||||
}
|
||||
|
||||
func fromBytes(b []byte, v interface{}) error {
|
||||
return json.Unmarshal(b, v)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user