Search code examples
node.jsmongodbmongoosediscord.js

E11000 duplicate key error collection error mongoose


ok so basically im getting this error and i dont know whats causing it

MongoServerError: Plan executor error during findAndModify :: caused by :: E11000 duplicate key error collection: test.profilemodels index: userID_1 dup key: { userID: "776359374783512608" }

i've literally tried dropping indexes and it still didnt work. all that works is when i drop my database/collection and i dont wanna have to do that everytime

my schema:

const mongoose = require("mongoose");

const profileSchema = new mongoose.Schema({
  userID: { type: String, require: true, unique: true },
  serverID: { type: String, require: true },
  coins: { type: Number, default: 200 },
  inventory: { type: Object },
  bank: { type: Number },
  bankSpace: { type: Number, default: 10000 },
  bankNotes: { type: Number },
  title: { type: String, default: 'Newbie'},
  badges: { type: String, default: 'None'},
  cPoints: { type: Number}
});

const model = mongoose.model("ProfileModels", profileSchema);

module.exports = model;

the code the error is coming from:

            const cpoints = profileData.cPoints
            if(cpoints < 10000) return message.reply('You don\'t have enough wins for this title!')

            await profileModel.findOneAndUpdate(
                {
                    userID: message.author.id,
                    title: 'Coinflipper'
                }
            );
            message.reply('Successfully equipped the **Coinflipper** Title!')

im stumped by this error hopefully someone can help


Solution

  • As you've pointed in your schema, the userID field has to be unique.

    With syntax below, you are telling to mongoose to update FIRST found document with userID that was already used by some other document. It's beacuse in that case first parameter is 'update' part.

    await profileModel.findOneAndUpdate(
      // update part 
       {
           userID: message.author.id,
           title: 'Coinflipper'
       }
    );
    

    So to fix it, you have to set some filtration in the first parameter, and in the second one 'fields to update'. So it will be like

      await profileModel.findOneAndUpdate(
         // filter part
        {
            userID: message.author.id
        },
        // update part 
        {
            title: 'Coinflipper'
        }
    );