Add timeseries, discriminator
This commit is contained in:
47
replace.go
Normal file
47
replace.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package mongo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
)
|
||||
|
||||
func (c *MongoClient) Replace(ctx context.Context, database, name string, id string, data bson.M) (bson.M, error) {
|
||||
collection := c.GetCollection(database, name)
|
||||
|
||||
filter := map[string]any { "_id": id }
|
||||
|
||||
var found bson.M
|
||||
err := collection.FindOne(ctx, filter).Decode(&found)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
prepareForReplace(data, found)
|
||||
|
||||
if err := c.DiscriminatorCheckAndApplyToData(ctx, name, data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateResult, err := collection.ReplaceOne(ctx, filter, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
PostReplace(updateResult, data, id)
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func PostReplace(updateResult *mongo.UpdateResult, data bson.M, id string) {
|
||||
if updateResult.ModifiedCount == 1 {
|
||||
data["_id"] = id
|
||||
}
|
||||
}
|
||||
|
||||
func prepareForReplace(data bson.M, old bson.M) {
|
||||
ensureNoId(data)
|
||||
ensureUpdatedAt(data)
|
||||
ensureExistingCreatedAt(data, old)
|
||||
}
|
||||
Reference in New Issue
Block a user