1

I'm creating index using mongoose it will check uniqueness of Name, PName and OName (Name+PName+OName should be unique). Please check below implementation

var MySchema = new mongoose.Schema({
                    Name: { type: String, required: true},
                    Details: [{
                        PName: { type: String, required: true},
                        OName: { type: String, required: true}
                    }]
                });

MySchema.index({Name: 1, Details.PName: 1, Details.OName:1 }, {unique: true});

Document

{"Name" : "Testing123","Details" : [{"PName" : "Page1", "OName" : "Ob1"}, 
    {"PName" : "Page1", "OName" : "Ob1"}]}

I need to restrict above document for insertion as the Name, PName and OName is not unique.

  • After an unique index is created mongo will throw an error if you are trying to insert duplicate data, and you can catch it in your code – Dan Ionescu Mar 28 '17 at 11:15
  • In Details subdocument, I have two objects with same PName and OName, need to restrict this entry.Successfully able to create index on this but it's not working on multiple objects in subdocument – Shweta12345 Mar 28 '17 at 12:34
  • It seems like they won't enforce uniqueness on subdocuments, check [this](http://stackoverflow.com/questions/25914973/mongoose-unique-index-on-subdocument) answer – Dan Ionescu Mar 28 '17 at 12:39

0 Answers0