How can I use partialFilterExpression on a mongoos

2019-08-19 12:50发布

I have created a mongoose model that has an email field. I want it to be unique if a value is provided by a user but I want it to be empty is a user has not provided any value. I have found a good mongodb reference here: https://docs.mongodb.com/manual/core/index-partial/#partial-index-with-unique-constraints that could work but I don't know how to make it work on mongoose

This is how the field looks like right now

email: {
    type: String,
    index: true,
    unique: true
  }

If I leave it the way it is, I cant create multiple documents with an empty/null email field

1条回答
冷血范
2楼-- · 2019-08-19 13:09

You can have something like :

email: {
    type: String,
    index: {
      unique: true,
      partialFilterExpression: { email: { $type: 'string' } },
    },
    default : null
  }

but do read below link, before you actually implement it, as defaults seems to work only on new document inserts :-

Mongoose v5.6.9 Documentation

查看更多
登录 后发表回答