Mike Schwörer
ae43cbb623
Some checks failed
Build Docker and Deploy / Run goext test-suite (push) Failing after 55s
77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
package wmo
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"gogs.mikescher.com/BlackForestBytes/goext/exerr"
|
|
)
|
|
|
|
func (c *Coll[TData]) FindOne(ctx context.Context, filter bson.M) (TData, error) {
|
|
mongoRes := c.coll.FindOne(ctx, filter)
|
|
if err := mongoRes.Err(); err != nil {
|
|
return *new(TData), exerr.Wrap(err, "mongo-query[find-one] failed").
|
|
Str("collection", c.Name()).
|
|
Any("filter", filter).
|
|
Build()
|
|
}
|
|
|
|
return c.decodeSingle(ctx, mongoRes)
|
|
}
|
|
|
|
func (c *Coll[TData]) FindOneOpt(ctx context.Context, filter bson.M) (*TData, error) {
|
|
mongoRes := c.coll.FindOne(ctx, filter)
|
|
|
|
res, err := c.decodeSingle(ctx, mongoRes)
|
|
if errors.Is(err, mongo.ErrNoDocuments) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, exerr.Wrap(err, "mongo-query[find-one-opt] failed").Any("filter", filter).Str("collection", c.Name()).Build()
|
|
}
|
|
|
|
return &res, nil
|
|
}
|
|
|
|
func (c *Coll[TData]) FindOneByID(ctx context.Context, id EntityID) (TData, error) {
|
|
mongoRes := c.coll.FindOne(ctx, bson.M{"_id": id})
|
|
if err := mongoRes.Err(); err != nil {
|
|
return *new(TData), exerr.Wrap(err, "mongo-query[find-one-by-id] failed").
|
|
Str("collection", c.Name()).
|
|
Id("id", id).
|
|
Build()
|
|
}
|
|
|
|
return c.decodeSingle(ctx, mongoRes)
|
|
}
|
|
|
|
func (c *Coll[TData]) FindOneOptByID(ctx context.Context, id EntityID) (*TData, error) {
|
|
mongoRes := c.coll.FindOne(ctx, bson.M{"_id": id})
|
|
|
|
res, err := c.decodeSingle(ctx, mongoRes)
|
|
if errors.Is(err, mongo.ErrNoDocuments) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, exerr.Wrap(err, "mongo-query[find-one-opt-by-id] failed").Id("id", id).Str("collection", c.Name()).Build()
|
|
}
|
|
|
|
return &res, nil
|
|
}
|
|
|
|
func (c *Coll[TData]) Find(ctx context.Context, filter bson.M, opts ...*options.FindOptions) ([]TData, error) {
|
|
cursor, err := c.coll.Find(ctx, filter, opts...)
|
|
if err != nil {
|
|
return nil, exerr.Wrap(err, "mongo-query[find-one-opt] failed").Any("filter", filter).Any("opts", opts).Str("collection", c.Name()).Build()
|
|
}
|
|
|
|
res, err := c.decodeAll(ctx, cursor)
|
|
if err != nil {
|
|
return nil, exerr.Wrap(err, "failed to decode values").Build()
|
|
}
|
|
|
|
return res, nil
|
|
}
|