0

I am trying to set up some functionality in a micro service to read from our MongoDB collection of users.

The functionality looks like this:

import myorgSchemas from '@myorg/myorgapp-schemas'
import mongoose from 'mongoose'

const UserModel = mongoose.model('User', myorgSchemas.user)

UserModel.findOne({ _id: '5a48d25bc5686a00436bda6f' }, (error, docs) => {
  console.log(error, docs)
})

When I run this, I first get the appropriate user object successfully. Then, about a second later, I get this error, which crashes the Node process:

MongoError: not authorized on myorg-production to execute command { insert: "system.indexes", documents: [ { ns: "myorg-production.users", key: { uniqueId: 1 }, name: "uniqueId_1", unique: true, background: true } ], ordered: true }

At first I thought this was something to do with the fact that the db-user I had created for this task was read-only (as it should be). But even after granting the user write ability, I get a different, similar error:

MongoError: E11000 duplicate key error index: myorg-production.users.$uniqueId_1 dup key: { : null }

For what it's worth, the DB is hosted with MLAB. Any idea what is happening here? Do I need to pass some kind of read-only flag into mongoose? If so I have not been able to find it anywhere.

john maccarthy
  • 5,463
  • 3
  • 11
  • 14
  • Hey, looks like you've added an index where `uniqueId` is set to be unique. If you insert a document without a value for `uniqueId`, the index will assume it to be `null`. If you add a second document without a `uniqueId` value, that's two values of null, so you'll get a duplicate key error. See this answer for more details: https://stackoverflow.com/a/24430345/2028838 – tfogo Jan 18 '18 at 19:00
  • Possible duplicate of [E11000 duplicate key error index in mongodb mongoose](https://stackoverflow.com/questions/24430220/e11000-duplicate-key-error-index-in-mongodb-mongoose) – tfogo Jan 18 '18 at 19:02

0 Answers0