Issues with attempting to Create a Compound Index

Hello, I have a similar but different problem. I am creating a database of different users, each of my objects contains 3 elements: an English word, an interpretation of the word and the user’s ID.
I want to allow different users to enter the same English word and the same interpretation, so that basically the only field that will differentiate between them will be the user ID field.
image
As you can see, the User ID field for me is the third field, and I manage to enter several different words with the same user ID.
But when I try to enter for a new user (with a different identification) a word that is already in the database but belongs to another user, I get a duplicate error for the first field.
(MongoServerError: E11000 duplicate key error collection: translationGame.words index: en_word_1 dup key: { en_word: “dall” } )
How do I solve this? how do I succeed entering the same word?
I searched the net but so far all the solutions given to me have not yielded the desired result.

You must create the appropriate compound unique index.

This thread has been solved and closed for more that 4 years. You should have started a new one.

I read the “Create a Compound Index” and i try this too without success. I want option for duplicate data in my fields, how can i do this?

Please share the index you created.

ok.

here is my code:

import { Schema, model } from 'mongoose';

export class Word {
    index: number;
    en_word: string;
    he_word: string;
    id: string;

    constructor({index, en_word, he_word, decodedUserId}: {index: number, en_word: string, he_word: string, decodedUserId: string}){
        this.index = index;
        this.en_word = en_word;
        this.he_word = he_word;
        this.id = decodedUserId;
    }
}

//deine a schema
export const WordSchema = new Schema({
    en_word: {
        type: String,
        required: true,
        //unique: true
    },
    he_word: {
        type: String,
        required: true,
        //unique: true 
    },
    decodedUserId: {
        type: String,
        required: true,  
    }
});

// Create a unique compound index for en_word, he_word, and decodedUserId
WordSchema.index({ en_word: 1, he_word: 1, decodedUserId: 1 }, { unique: true });

export const WordModel = model("word", WordSchema)

here is my code (cleaner):

import mongoose, { Schema, model } from 'mongoose';
import { UserModel } from '../users/userModel';

export class Word {
    en_word: string;
    he_word: string;

    constructor({en_word, he_word}: {en_word: string, he_word: string}){
        this.en_word = en_word;
        this.he_word = he_word;
    }
}

//deine a schema
export const WordSchema = new Schema({
    en_word: {
        type: String,
        required: true,
    },
    he_word: {
        type: String,
        required: true,
    },
});

// Create a unique compound index for en_word, he_word, and decodedUserId
WordSchema.index({ en_word: 1, he_word: 1}, { unique: true });

export const WordModel = model("word", WordSchema)

export const words: Word[] = [];

const UserWordsSchema = new mongoose.Schema({
    wordsId: {type: Schema.Types.ObjectId, ref: WordModel},
    userId: {type: Schema.Types.ObjectId, ref: UserModel},
});

export const UserWordsModel = mongoose.model("userwords", UserWordsSchema);

I getting over and over the same MongoServerError: E11000 duplicate key error collection. this time it show keyValue: { index: null }.

how can i fix this bug?

Your code is wrong and does not match the comment as the field decodedUserId is not part of the index.

the commet is wrong. the wordSchema dose not have decodedUserId.

So it means that we are trying to hit a moving target. I saw in an earlier post that decodedUserId was in the WordSchema

and your original issue

seems to indicate that you want to allow the same word by a different decodedUserId. This means decodedUserId must be part of the unique index.

ok.
I try it. got the error again.
here is my fixed code, as you suggested I added the decodedUserId to my wordSchema and to the WordSchema.index:

import mongoose, { Schema, model } from 'mongoose';
import { UserModel } from '../users/userModel';

export class Word {
    // index: number;
    en_word: string;
    he_word: string;
    id: string;

    constructor({en_word, he_word, decodedUserId }: {en_word: string, he_word: string, decodedUserId: string}){
        // this.index = index;
        this.en_word = en_word;
        this.he_word = he_word;
        this.id = decodedUserId;
    }
}

//deine a schema
export const WordSchema = new Schema({
    en_word: {
        type: String,
        required: true,
        //unique: true
    },
    he_word: {
        type: String,
        required: true,
        //unique: true 
    },
    decodedUserId: {
        type: String,
        required: true,  
    }
});

// Create a unique compound index for en_word, he_word
WordSchema.index({ en_word: 1, he_word: 1, decodedUserId: 1}, { unique: true });

export const WordModel = model("word", WordSchema)

export const words: Word[] = [];

const UserWordsSchema = new mongoose.Schema({
    wordsId: {type: Schema.Types.ObjectId, ref: WordModel},
    userId: {type: Schema.Types.ObjectId, ref: UserModel},
});

// Create a unique compound index for UserWordsSchema
UserWordsSchema.index({ wordsId: 1, userId: 1}, { unique: true });

export const UserWordsModel = mongoose.model("userwords", UserWordsSchema);

I succeeded in adding the first word to the DB but when I tried to add the second word to the same user I got the same error:

MongoServerError: E11000 duplicate key error collection: translationGame.words index: index_1 dup key: { index: null }
at D:\GitRepo\translate_game_with_DB\translate-game-with-DB\node_modules\mongoose\node_modules\mongodb\src\operations\insert.ts:85:25
at D:\GitRepo\translate_game_with_DB\translate-game-with-DB\node_modules\mongoose\node_modules\mongodb\src\operations\command.ts:173:14
at processTicksAndRejections (node:internal/process/task_queues:95:5) {
index: 0,
code: 11000,
keyPattern: { index: 1 },
keyValue: { index: null },
[Symbol(errorLabels)]: Set(0) {}
}

how can I see (in my consol.log for example) the keyValue of the index (the one I get null all the time)? there is a way to get it?
my code is as shown in the documentation of the process, what am I doing wrong?

The error message indicates an error with index

but your schema defines index

They do not match. I do not know Mongoose but my guess is that the indexes are not update in the database when your code is updated. Probably because the collection already exist. I think that you previously had a unique index of a field named index. Now that this field is not part of your schema, its value is always null.

To confirm what I suspect go into mongosh and run getIndexes() on your collection.

The screenshot in your original post confirms that you had once a field named index in your schema.

indeed I had an index field on my wordSchema, I did it after getting this error because I thought it would help, but it didn’t.

I don’t have mongosh and I never work with it.

there is anything else that I can do to solve this error?

You may do the same with Compass.

You have to remove the index.

I have spent time working on your issue. I would appreciate closure.

hi, sorry, my first time :smile:
Your advice didn’t help me in the end, but I learned a lot from it.
In the end, what solved the problem was that I had to reset the DB, the indexes and everything, I didn’t know that this had to be done, and there was no information about it on any website or forum and a A friend in the field asked me about it and that’s how I realized that this is what needs to be done.
Many thanks for your help.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.