简体   繁体   中英

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.

EDIT: Documents which should match, without conflict (currently conflicting): I have a first customer with id customer_id: 11111 . Now I want to add another customer, who can have customer_id: 22222 , customer_id: '' or customer_id: null , but not customer_id: 11111 .

MongoDB shell / db version: 3.4.4 Mongoose: 4.9.7

Any idea ?

我认为这将帮助您解决问题: https : //www.npmjs.com/package/mongoose-auto-increment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM