Search code examples
mongodbvalidationindexingmongooseunique

Are field level uniqueness constraints still supported in Mongo(ose)?


It looks like mongoose supported field level uniqueness constraints in earlier versions as follows (seen in 2.7.x here):

var SomeSchema = new Schema ({
  field: {index: {unique: true}} // field level
})

I can't find any reference to it in the 4.4.x docs. Is the preferred way to do this on the schema level now, like so (seen in 4.4.x here):

SomeSchema.index({field: 1}, {unique: true}) // schema level

Solution

  • Yes, unique indexes are still supported in Mongoose; see here and here in the current docs.

    Examples from the linked docs:

    var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }});
    var s = new Schema({ name: { type: String, unique: true }});
    
    Schema.path('my.path').index({ unique: true, sparse: true });
    Schema.path('name').index({ unique: true });