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

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

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 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