1

I'm trying to create a Project entry, it has a languages array which I want to describe as

languages can (will) be initially empty [], and each object within it must have a field called key which must be unique.

e.g:

{
  languages: [],
  ....
}

or:

{
  languages: [ { key: 'en-US } ],
  ...
}

The mongoose Schema looks like:

{
  languages: [{
    key: {
      type: String,
      unique: true,
    },
  }],
  ...
}

The first creation works:

const project = new Project({
  name,
  owner: user,
});

await project.save();

However thereafter I get this error about already having a language with key: null, even though the languages array is empty...

{ MongoError: E11000 duplicate key error collection: yebu.projects index: tags.name_1 dup key: { : null }
    at Function.MongoError.create (<redacted>/node_modules/mongodb-core/lib/error.js:31:11)
...

I tried sparse: true in the key field but to no avail.

0

2 Answers 2

1

As this answer mentions: Mongodb unique sparse index

The answer was to combine unique: true with sparse: true. I wasn't noticing that it was working as my next collection in the schema was failing until I added it there too.

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

Comments

0

Try this - combine unique: true, sparse: true with default: null

{
  languages: [{
    key: {
      type: String,
      default: null
      unique: true,
    },
  }],
  ...
}

Comments

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.