I am new to GO language and I am using MongoDB with it. I am creating a backend for an application and its frontend on Angular 4. I want to check if collection exists or not.
Here is my code and I have checked it using nil.
collection := GetCollection("users")
fmt.Println("collection", collection)
if collection == nil {
fmt.Println("Collection is empty")
}
I have created a GetCollection function which return a collection when we pass it a collection name. So when if there is no collection how can I check that if it exists or not? I have tried many things but failed.
You may simply use the
Database.CollectionNames()
method which returns the collection names present in the given db. It returns a slice in which you have to check if your collection is listed.But as Neil Lunn wrote in his comments, you shouldn't need this. You should change your logic to use MongoDB not to rely on this check. Collections are created automatically if you try to insert a document, and querying from non-existing collections yields no error (and no result of course).