Friday, 5 May 2017

MongoDB: how to use unique and optional index in mongoose schema?

Here is my field in my Mongoose schema:

var userSchema = moongoose.Schema({
  ...
  customer_id: {
    type: Number,
    trim: true
  }
  ...
}, {
  timestamps: true
});

I want this field to be unique, and also accepts from clients things like "", null or undefined.

1) I tried this:

customer_id: {
  type: Number,
  trim: true,
  index: {
    unique: true,
    partialFilterExpression: {customer_id: {$type: 'number'}}
  }
}

2) Also this:

customer_id: {
  type: Number,
  trim: true,
  index: {
    unique: true,
    partialFilterExpression: {customer_id: {$exists: true}}
  }
}

3) And this:

customer_id: {
  type: Number,
  trim: true,
  unique: true,
  sparse: true
}

These don't work.

I reset my collection every time between each test, and still have a 409 Conflict error when I add a second customer.

MongoDB shell / db version: 3.4.4 Mongoose: 4.9.7

Any idea ?



via Pierre Hofman

No comments:

Post a Comment