Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!