Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda