MongoDB node js driver createIndex runs fine but no index is created

52 views Asked by At

I am using mongodb nodejs driver version v6.2 for mongodb docker image 6.0.4. I have a replica set initialized (1 primary, 2 secondary) and running fine (all other calls and operations run fine). I am connecting using MongoClient from the nodejs driver with the following connection string:

mongodb://db-replica-1:27017,db-replica-2:27018,db-replica-3:27019/?replicaSet=dbrs

After making the following calls:

userCollection = mongoClient.db(databaseName).collection<UserDb>('User')
const o2 = await userCollection.createIndex({ "username": 1 }, { unique: true, name: "username_constraint" })

Where UserDb is just TypeScript interface which does have, among others, the username field as a string.

When I run this, it runs fine, and if I print:

await userCollection.listIndexes().toArray()

I get the right indexes, but when I check the "databaseName" database ,collection 'User', via compass or shell, there are no indexes.

What makes it even more weird, if I change the name of the database in this call:

userCollection = mongoClient.db(databaseName + '1').collection<UserDb>('User')

it surprisingly works!

Any help appreciated!

1

There are 1 answers

0
AldiT On BEST ANSWER

After a while trying to debug, I finally found what the problem was!

Some context first: I am trying to run this as an integration test where the case is to simply create an uniqueness index and check that it is enforced on write.

The problem was very stupid:

  1. I create the indexes on init
  2. I clean the database before the tests ran

The latter cleanup, also cleaned the indexes therefore having no indexes on future writes. After calling the cleanup method only at the end of the tests (not the beginning) everything looks fine now!