Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
Unique Compound Constraints not working with ensureIndex?

I have a DB called participants with structure:

{
  _id: '123',
  infos: [
    {
      myId: 'my123',
      otherId: 'other123'
    }
  ]
}

However, studyInfos can be empty and the objects inside of studyInfos can contain a myId without a otherId. I want to create a unique index on

{ myId: 1, otherId: 1}

I am using ensureIndex like so:

  Participants._ensureIndex(
    { 'infos.myId': 1, 'infos.otherId': 1 },
    {
      unique: true,
      sparse: true,
      partialFilterExpression: {
        'infos.otherId': { $exists: true, $type: String, $ne: null },
        'infos.myId': { $exists: true, $type: String, $ne: null },
      },
    },
  );

However, when i try to add a second user with infos empty or two users with otherId missing in both it fails due to duplicate index. Basically the only duplicate I don't want is

{
  _id: '123',
  infos: [
    {
      myId: 'my123',
      otherId: 'other123'
    }
  ]
},
{
  _id: '456',
  infos: [
    {
      myId: 'my123',
      otherId: 'other123'
    }
  ]
},

But its not allowing:

{
  _id: '123',
  infos: []
},
{
  _id: '456',
  infos: []
},

or

{
  _id: '123',
  infos: [
    {
      myId: 'my123',
    }
  ]
},
{
  _id: '456',
  infos: [
    {
      myId: 'my123',
    }
  ]
},

either despite my usage of partialFilterExpression and sparse.

Help.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Answering my own question, it was two things:

  1. Can't use sparse and partialFilterExpression together - although I had tried versions of this without both and still didn't work
  2. EnsureIndex is deprecated so it needed to use Participants.rawCollection().createIndex and delete my old index

Final Answer:

  Participants.rawCollection().createIndex(
    { 'infos.myId': 1, 'infos.otherId': 1 },
    {
      unique: true,
      partialFilterExpression: {
        'infos.otherId': { $exists: true },
        'infos.myId': { $exists: true },
      },
    },
  );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda