goext/wmo/queryInsert.go

56 lines
2.1 KiB
Go
Raw Permalink Normal View History

2023-06-06 21:33:49 +02:00
package wmo
import (
"context"
"go.mongodb.org/mongo-driver/bson"
2023-07-24 09:16:37 +02:00
"go.mongodb.org/mongo-driver/mongo"
2023-08-21 15:08:35 +02:00
"gogs.mikescher.com/BlackForestBytes/goext/exerr"
2023-07-24 09:16:37 +02:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
2023-06-06 21:33:49 +02:00
)
func (c *Coll[TData]) InsertOne(ctx context.Context, valueIn TData) (TData, error) {
insRes, err := c.coll.InsertOne(ctx, valueIn)
if err != nil {
2023-08-21 15:08:35 +02:00
return *new(TData), exerr.Wrap(err, "mongo-query[insert-one] failed").Str("collection", c.Name()).Build()
2023-06-06 21:33:49 +02:00
}
r, err := c.findOneInternal(ctx, bson.M{"_id": insRes.InsertedID}, false)
if err != nil {
return *new(TData), exerr.Wrap(err, "mongo-query[insert-one] failed").Str("collection", c.Name()).Build()
}
return *r, nil
2023-06-06 21:33:49 +02:00
}
2023-11-09 09:35:56 +01:00
// InsertOneUnchecked behaves the same as InsertOne, but allows arbitrary data to be inserted (valueIn is any instead of TData)
func (c *Coll[TData]) InsertOneUnchecked(ctx context.Context, valueIn any) (TData, error) {
insRes, err := c.coll.InsertOne(ctx, valueIn)
if err != nil {
return *new(TData), exerr.Wrap(err, "mongo-query[insert-one] failed").Str("collection", c.Name()).Build()
}
r, err := c.findOneInternal(ctx, bson.M{"_id": insRes.InsertedID}, false)
if err != nil {
return *new(TData), exerr.Wrap(err, "mongo-query[insert-one] failed").Str("collection", c.Name()).Build()
}
return *r, nil
}
2023-07-24 09:16:37 +02:00
func (c *Coll[TData]) InsertMany(ctx context.Context, valueIn []TData) (*mongo.InsertManyResult, error) {
2023-08-21 15:08:35 +02:00
insRes, err := c.coll.InsertMany(ctx, langext.ArrayToInterface(valueIn))
if err != nil {
return nil, exerr.Wrap(err, "mongo-query[insert-many] failed").Int("len(valueIn)", len(valueIn)).Str("collection", c.Name()).Build()
}
return insRes, nil
}
2023-11-09 09:36:41 +01:00
// InsertManyUnchecked behaves the same as InsertOne, but allows arbitrary data to be inserted (valueIn is []any instead of []TData)
func (c *Coll[TData]) InsertManyUnchecked(ctx context.Context, valueIn []any) (*mongo.InsertManyResult, error) {
insRes, err := c.coll.InsertMany(ctx, langext.ArrayToInterface(valueIn))
if err != nil {
return nil, exerr.Wrap(err, "mongo-query[insert-many] failed").Int("len(valueIn)", len(valueIn)).Str("collection", c.Name()).Build()
}
return insRes, nil
}