1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I feel myself really stupid. When I launched code example above - it created an unique index. I can't get why when I use this code: gyazo.com/d57dba0ebdb6ee9dd9693d38779979fa I don't get unique index. Even output is the same - there is no error. But, created index is not unique: gyazo.com/78c236b5f93ace768d4acdbcc0c58554 According documentation promises are available. What it can be?
I wrote my own promise and it works as expected: gyazo.com/f83282644299320607904874c89827c1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.