0

I'm trying to set an unique index for the property userID in my subdocument User, with is used as an array in my Class schema. The index should be for each Class and not a global index for all classes.

So Class A should for example be able to have the userIDs [1,2,3,4] and Class B [2,3,4,7,9]. What should not be allowed is: Class A [1,2,2,3] The following query gives me an exception:

E11000 duplicate key error collection: app.classes index: _users.userID_1 dup key: { : 1.0 }

Query

db.classes.update(
  { _id: ObjectId("597f6864694ff43ddca09eaf") },
  { $push: { _users: {userID: 1}}} 
);

Schema

var userSchema = new Schema({
    userID:             {type: Number, unique: true}, 
    // ...
};

mongoose.model('User', userSchema);

var classSchema = new Schema({
    _users:         {type: [userSchema]},
    // ...
});

mongoose.model('Class', classSchema);

db.class.find({});

[
  {
    "_id": "597df15eb0b0bd17c985df05",
    "_users": [
      {
        "_id": "597e9d373f01d64b66b9249f",
        "userID": 1,
      },
      {
        "_id": "597f6892694ff43ddca09eb0",
        "userID": 2,
      }
    ],
  },
  {
    "_id": "597f6864694ff43ddca09eaf",
    "_users": [],
  }
]
Chris
  • 4,255
  • 7
  • 42
  • 83

0 Answers0