How to check if Collection or Index exists?

Hi.
I’m using couchbase sdk 4.4.4 with node 20.
I want to create a Collection or an index (of a collection) if they do not exist.
I tried a couple of ways, but failed to check it.

Could you please advice me how to do it?
Thanks in advance.

Hi @jinchong – Determining if a collection exists can be a bit involved. A quick approach can be using the CollectionManger’s (bucket.collections() returns a CollectionManager, see API docs - bucket.collections(), API docs - CollectionManager) getAllScopes() method. You can then look through the scopes and the collections w/in the scope to see if the collection exists. For a more thorough, but involved, method see the Node.js SDK tests (example here, specifically look into the consistencyUtils operations).

For creating an index on a collection, if it does not exist, you can use the CollectionQueryIndexManager’s createIndex() method and be sure to pass in ignoreIfExists: true in the options. See API Docs for details. That way the index is only created if it doesn’t exist.

I hope this helps.

1 Like

Sometimes I just do an operation on a collection to see if the collection exists.

Thanks a lot. I found it.
I’m still curious why CollectionManger ( from bucket.collections()) doesn’t provide this list. :wink: