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

152
Visualizações
ObjectIDs in other collections without getting duplicate key error

I am getting the following error when trying to create a document in a collection.

MongoServerError: E11000 duplicate key error collection: stock-trading-system-db.trades index: user_id_1 dup key: { user_id: ObjectId('6266de71b90b594dab9037f3') }

Here is my schema:

const tradeSchema = new mongoose.Schema({
    user_id: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    stock_id: {
        type: Schema.Types.ObjectId,
        ref: 'Stock',
        required: true
    },
    stock_amount: {
        type: Number,
        required: true
    },
    stock_value: {
        type: Number,
        required: true
    },
    time_of_trade: {
        type: Date,
        required: true,
        default: new Date()
    },
    trade_status: {
        type: String,
        enum: ['Approved', 'Declined', 'Pending'],
        required: true,
        default: 'Pending'
    }
}, { collection: 'trades' })

I don't want user_id and stock_id to be unique, i just want it to check that those ObjectIDs exist in their respective collections before making the trade document. How do i achieve this?

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

0

It looks like a collection saves the schema that is defined in mongoose, and even if you change the schema, the unique values will stay the same inside the collection.

So even though i had removed

unique: true;

from my mongoose schema, it hadn't removed this from the collection in my DB.

Therefore the solution to this is to delete the collection and recreate it.

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