1

I have added unique key index as suggested in the mongoose and mongoDB documentation but when I try to insert multiple question using insertMany it doesn't throw an error on duplicate items. Am I doing something wrong here?

Question.insertMany(questions);

const NotRequiredStringSchema = { type: String, required: false, default: '' };

const Question = new Schema({
    "type": {
        type: String,
        trim: true,
        enum: Object.values(questionTypes),
        required: 'Question type is required'
    },
    "text": {
        type: String,
        required: true
    },
    "desc": NotRequiredStringSchema,
    "options": [{
        "id": ObjectId,
        "name": NotRequiredStringSchema,
        "helperText": NotRequiredStringSchema,
        "icon_key": NotRequiredStringSchema,
        "icon_url": NotRequiredStringSchema,
        "icon_svg": NotRequiredStringSchema
    }]
});

Question.index({
    type: 1,
    text: 1
}, {
    unique: true
});

const model = mongoose.model('Question', Question);

module.exports = model;
  • The typical problem is that you first created that index w/o unique: true. See https://stackoverflow.com/questions/30966146/mongoose-schema-unique-not-being-respected – JohnnyHK Oct 22 '18 at 13:40
  • 1
    @JohnnyHK I had dropped the collection and then again tried it. Won't it work then? – Abhinav Jain Oct 22 '18 at 18:53
  • @AbhinavJain any update on this? I am having same issue, it worked for the first time but then it's not after i dropped my that collection – 1UC1F3R616 Oct 09 '20 at 20:11

0 Answers0