Maurice
Maurice

Reputation: 169

Duplicate error even though collection is empty

I try to insert multiple documents into my MongoDB collection, but whatever I do, I get a duplicate error. I made sure that there should be no duplicates possible by dropping the whole collection.

I tried it with .insertMany(), .save(), .create() - none of them do work. Though the docs get inserted, I still get the duplicate error 11000.

My function to insert the docs:

Words.prototype.addManyGeneralWordsEN = async function(words) {
    await generalWordEN.create(words).then((res) => {
        console.log(res)
    })
    .catch((err) => {
        console.log(err.code)
    })
}

// add words to database
await this.addManyGeneralWordsEN(wordsToAdd)

My schema:

const generalWordENSchema = new mongoose.Schema(
  {
    german: {
      type: String, 
      required: true
    },
    english: {
      type: String, 
      required: true
    },
    partOfSpeech: {
      required: true,
      type: String
    },
    example: {
      default: null,
      type: String, 
    },
    defintion: {
      default: null,
      type: String, 
    },
    image: {
      default: null,
      type: String, 
    },
    audio: {
      default: null,
      type: String, 
    },
    level: {
      default: null,
      type: Number, 
    },
  }
)

generalWordENSchema.index({ german: 1, english: 1, partOfSpeech: 1}, { unique: true })

module.exports = generalWordENSchema

My sample data:

[
  {
    "english": "clothes",
    "german": "Kleidung",
    "partOfSpeech": "noun",
    "example": "My wife's wardrobe is filled with beautiful clothes.",
    "definition": "",
    "image": "",
    "audio": "",
    "level": ""
  },
  {
    "english": "men's clothing",
    "german": "Herrenbekleidung",
    "partOfSpeech": "noun",
    "example": "Men's clothing is on the second floor.",
    "definition": "",
    "image": "",
    "audio": "",
    "level": ""
  }
]

Upvotes: 0

Views: 458

Answers (1)

Rafael Freitas
Rafael Freitas

Reputation: 201

The problem is probably on this line

generalWordENSchema.index({ german: 1, english: 1, partOfSpeech: 1}, { unique: true })

You created an index for the collection and used partOfSpeech as unique, but you have two documents with the same value noun.

It should work if you change it to:

generalWordENSchema.index({ german: 1, english: 1 }, { unique: true });

You also have a typo on the Schema declaration that might cause you different issues. You typed defintion instead of definition.

Upvotes: 1

Related Questions