Skip to content

Instantly share code, notes, and snippets.

@magicwenli
Created November 3, 2021 05:57
Show Gist options
  • Save magicwenli/83a8471b0fb643cd282beb920a10d39a to your computer and use it in GitHub Desktop.
Save magicwenli/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
// 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