0

I currently create an index by:

In package db:

// CreateUniqueIndex create UniqueIndex
func CreateUniqueIndex(collection string, keys ...string) {
    keysDoc := bsonx.Doc{}
    for _, key := range keys {
        if strings.HasPrefix(key, "-") {
            keysDoc = keysDoc.Append(strings.TrimLeft(key, "-"), bsonx.Int32(-1))
        } else {
            keysDoc = keysDoc.Append(key, bsonx.Int32(1))
        }
    }
    idxRet, err := database.Collection(collection).Indexes().CreateOne(
        context.Background(),
        mongo.IndexModel{
            Keys:    keysDoc,
            Options: options.Index().SetUnique(true),
        },
        options.CreateIndexes().SetMaxTime(10*time.Second),
    )
    if err != nil {
        log.Fatal(err)
    }
    log.Println("collection.Indexes().CreateOne:", idxRet)
}

And in the main.go file:

db.CreateUniqueIndex("User", "email")

My concern is that the index will be created when I start the server. However, what if a user creates an account and will his email be index?

So, please advise the correct way to handle mongodb index.

The questioner
  • 724
  • 10
  • 21
  • What do you mean by starting the server? How does a user create without a server up and running? please explain – Gibbs Aug 19 '20 at 14:28
  • `go run main.go` to start the server. I just want to know if my implementation of the email indexing is correct or there may be better ways to do so. – The questioner Aug 21 '20 at 17:04

0 Answers0