Gordienko R.
Gordienko R.

Reputation: 341

Creating unique index via mongodb native driver

There is a code:

const { MongoClient } = require('mongodb')

const db = MongoClient.connect('mongodb://172.17.0.2:27017/test')
db
  .then(
    async dataBase => {
      eduDb = dataBase.db('edu-service-accounts')
      const accounts = eduDb.collection('accounts')
      await accounts.createIndex({ email: 1 }, { unique: true })
      accounts.insertOne({ email: '123' })
    }
  )

Code above creates an index, but that is no unique. I already read official docs for native mongoDB driver, but can't handle it. And yes, I've deleted all old indexex before testing that code.

Can someone please show a code that really create an index with unique. I mean not part of official doc, or something like that - I need code that works. NOTE: I tested that code with local db and mlab - the same result.

Upvotes: 1

Views: 3129

Answers (1)

rieckpil
rieckpil

Reputation: 12051

Like the documentation says: db.createIndex(collectionname, index[, options], callback) the creation returns an index. Try to log the result of the callback. Maybe you are getting an error from the db.

Try something like:

 // your connection stuff
accounts.createIndex({ email: 1 }, { unique: true }, function(err, result) {
   if(err) {
      console.log(err);

   } else {
     console.log(result);
  } 
});

After that please provide us the logs.

Upvotes: 2

Related Questions