rimi
rimi

Reputation: 53

Mongoose Schema array can be the same over multiple documents

I have the following schema setup:

//character.js in models/character.js
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
const CharacterSchema  = new mongoose.Schema({
    // defines the character name
    name: {
        type  : String
    },
    // list of the mission ids
    missionList: [ Number ]
});
const Character= mongoose.model('Character', CharacterSchema);
module.exports = Character;

I can create new characters and store them in the database. Also I have stored some missions in the database that can be found via the id. The character should only have an array of ids to not duplicate the missions with multiple characters. The mission schema looks like this:

//mission.js in models/mission.js
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
const MissionSchema  = new mongoose.Schema({
    // defines the mission name
    name: {
        type  : String,
        required : true
    },
    // defines the id of the current mission
    id: {
        type: Number,
        required : true
    }
});
const Mission = mongoose.model('Mission', MissionSchema);
module.exports = Mission;

Now when I create a character it is working fine but when I create the second character with the same values inside the missionList array it is raising the following error:

(node:18) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: space-test.character index: missionList.name_1 dup key: { missionList.name: null }

Here is how I create the characters:

var char1 = new Character({ name: "Bambi", missionList: [0, 1, 2, 3, 4, 5, 6, 7]}; 
char1.save();// working fine

var char2 = new Character({ name: "R2D2", missionList: [0, 1, 2, 3, 4, 5, 6, 7]}; 
char2.save();// throwing the error

Am I wrong in using my mongoose schema? I do not declare the missionList as unique so it should be possible that they are the same in multiple characters.

Any advice or help how to work around this?

Upvotes: 0

Views: 37

Answers (1)

Joe
Joe

Reputation: 28346

At some point a unique index was created on {"missionList.name":1}.

You will need to remove that index to avoid that error.

Upvotes: 1

Related Questions