47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package mongo
|
|
|
|
import (
|
|
"context"
|
|
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
)
|
|
|
|
|
|
// InsertOneWithStruct can be used to insert defined structs.
|
|
func (c *MongoClient) InsertOneFromStruct(ctx context.Context, database, name string, data any) (bson.M, error) {
|
|
o, err := ToMap(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return c.InsertOne(ctx, database, name, o)
|
|
}
|
|
|
|
// InsertOne will add missing ids and the created date before saving to the database.
|
|
func (c *MongoClient) InsertOne(ctx context.Context, database, name string, data bson.M) (bson.M, error) {
|
|
collection := c.GetCollection(database, name)
|
|
|
|
prepareForInsert(data, c.GetIdPrefix(name))
|
|
|
|
if err := c.DiscriminatorCheckAndApplyToData(ctx, name, data); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if _, err := collection.InsertOne(ctx, data); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return data, nil
|
|
}
|
|
|
|
// prepareForInsert takes a map[string]any and:
|
|
// * adds a new _id if property does not exist or is an empty string
|
|
// * adds/updates property created_at using the current timestamp.
|
|
func prepareForInsert(data bson.M, idPrefix string) {
|
|
ensureId(data, idPrefix)
|
|
ensureCreatedAt(data)
|
|
ensureUpdatedAt(data)
|
|
}
|
|
|
|
|