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

1K
Visualizações
Mongoose: Unique field if it's not null or an empty string

So, I have the following schema:

const Players = new mongoose.Schema({
    discordID: {
    type: String,
    unique: true,
    required: function () {
        return typeof this.discordID !== "string" && this.discordID !== null
    }
})

My point is to make discordID unique, but only if it's not null or "".

I heard about sparse, but it doesn't seem to work as I want it to. I get duplication errors every time I'm trying to insert 2+ documents with discordID set to null (I tried sparse: true and index: {sparse: true, unique: true}).

Is there something I can do? I want to keep this validation on the schema level if it's only possible.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Sparse indexes work for documents that omit the key. The required discordID is included and set to null which is passed onto the data store.

https://docs.mongodb.com/manual/core/index-sparse/

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field.

Set fields to undefined in mongoose for them to be removed before save.

over 4 years ago · Santiago Trujillo 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