74 lines
1.5 KiB
Go
74 lines
1.5 KiB
Go
|
package wmo
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"go.mongodb.org/mongo-driver/bson"
|
||
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
)
|
||
|
|
||
|
func (c *Coll[TData]) FindOne(ctx context.Context, filter bson.M) (TData, error) {
|
||
|
var res TData
|
||
|
|
||
|
err := c.coll.FindOne(ctx, filter).Decode(&res)
|
||
|
if err != nil {
|
||
|
return *new(TData), err
|
||
|
}
|
||
|
|
||
|
return res, nil
|
||
|
}
|
||
|
|
||
|
func (c *Coll[TData]) FindOneOpt(ctx context.Context, filter bson.M) (*TData, error) {
|
||
|
var res TData
|
||
|
|
||
|
err := c.coll.FindOne(ctx, filter).Decode(&res)
|
||
|
if err == mongo.ErrNoDocuments {
|
||
|
return nil, nil
|
||
|
}
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return &res, nil
|
||
|
}
|
||
|
|
||
|
func (c *Coll[TData]) FindOneByID(ctx context.Context, id EntityID) (TData, error) {
|
||
|
var res TData
|
||
|
|
||
|
err := c.coll.FindOne(ctx, bson.M{"_id": id}).Decode(&res)
|
||
|
if err != nil {
|
||
|
return *new(TData), err
|
||
|
}
|
||
|
|
||
|
return res, nil
|
||
|
}
|
||
|
|
||
|
func (c *Coll[TData]) FindOneOptByID(ctx context.Context, id EntityID) (*TData, error) {
|
||
|
var res TData
|
||
|
|
||
|
err := c.coll.FindOne(ctx, bson.M{"_id": id}).Decode(&res)
|
||
|
if err == mongo.ErrNoDocuments {
|
||
|
return nil, nil
|
||
|
}
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
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, err
|
||
|
}
|
||
|
|
||
|
res := make([]TData, 0, cursor.RemainingBatchLength())
|
||
|
err = cursor.All(ctx, &res)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return res, nil
|
||
|
}
|