A unique index on an array

149 views
Skip to first unread message

dbrand666

unread,
Jul 20, 2012, 3:10:37 PM7/20/12
to mongoo...@googlegroups.com
My schema contains an array or strings.  I want to put a unique, sparse index on this array, like so:

new Schema({
  array_of_strings: {type: [String], unique: true, sparse: true}
});

The problem I'm running into is that if array_of_strings is empty, Mongoose includes the empty array in the document. This leads to duplicate key errors. It there a way to tell Mongoose not to include empty objects when writing documents?
Message has been deleted
Message has been deleted

dbrand666

unread,
Aug 3, 2012, 4:20:08 PM8/3/12
to mongoo...@googlegroups.com
This is the workaround I ended up with:

MySchema.pre('save', function (cb) {
  if (this.array_of_strings && this.array_of_strings.length === 0) {
    this.array_of_strings = undefined;
  }
  cb();
});

I still don't understand why Mongoose insists on trying to write all these empty arrays.
Reply all
Reply to author
Forward
0 new messages