1
votes

I was trying to delete a specific value (a game) from my array in my schema, and this is the code:

User.update({ userName: user }, { $pull: { games: { _id: deleteItem } } }, function (err, val) {
    console.log(err);
});

the schema:

const userSchema = new mongoose.Schema({
    userName: { type: String, index: true, unique: true },
    userPassword: String,
    games: [gameSchema]
});

the error:

MongoError: E11000 duplicate key error collection: mountain.users index: games.password_1 errmsg: 'E11000 duplicate key error collection: mountain.users index: games.password_1 dup key: { games.password: null }', [Symbol(mongoErrorContextSymbol)]: {} }

why is the error apear and how can I solve it?/other way to delete a value from array inside on object

thanks for your help!

1
Please include the following in the post: db.collection.getIndexes() output.prasad_
Maybe you have another document, in which games.password does not exist. You can consider deleting the index: user.games.password.noam
@noam I have passwords in all gamesORI
@prasad_ I tried to console it and I got an error "TypeError: User.getIndexes is not a function"ORI
@ORI, but after your update, there should be no password for this particular game, right? It seems that this has already happened, that someone updated one document to $pull the password away from it.noam

1 Answers

0
votes

You have a unique index built on games. password array.

I assume the game you're trying to pull is the last game in the array. and that you already have a document with an empty games array.

Hence the value of both of those documents for the index is (null) the same as they both don't exist.

sparse indexes exist for this very reason, it allows you to benefit from the unique behaviour while only taking under account documents with values that exist.

So basically you have to re-built your index to be a unique + sparse one.