Created
November 3, 2021 05:57
-
-
Save wesleyel/83a8471b0fb643cd282beb920a10d39a to your computer and use it in GitHub Desktop.
Create a collection called idgen, create a document for every other collection, and store the self-add id
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a collection called idgen, create a document for every other collection, | |
// and store the self-add id | |
import ( | |
"context" | |
"go.mongodb.org/mongo-driver/bson" | |
"go.mongodb.org/mongo-driver/mongo" | |
"go.mongodb.org/mongo-driver/mongo/options" | |
) | |
type idGenerate struct { | |
ID int | |
KEY string | |
} | |
func Next(coll string) (int, error) { | |
update := bson.M{"$inc": bson.M{"id": 1}} | |
idG := idGenerate{ID: 1} | |
err := database.Collection("idgen"). | |
FindOneAndUpdate(context.Background(), bson.M{"key": coll}, update).Decode(&idG) | |
if err == mongo.ErrNoDocuments { | |
_, err := database.Collection("idgen").InsertOne(context.Background(), bson.M{"key": coll, "id": 1}) | |
if err != nil { | |
ec <- err | |
return 0, nil | |
} else { | |
return 0, nil | |
} | |
} else if err != nil { | |
ec <- err | |
return 0, err | |
} else { | |
return idG.ID, nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment