Sunday, 19 March 2017

How do I create mongoose unique index with specific value?

I have collection named TradeRequest with the following schema

const TradeRequestSchema = mongoose.Schema({
  status: {
    type: String,
    enum: ["opened", "rejected", "accepted"],
    default: "opened"
  },

  _requester: {
    required: true,
    type: mongoose.Schema.Types.ObjectId
  },

  _requestedBook: {
    required: true,
    type: mongoose.Schema.Types.ObjectId
  }
});

My database should have only one open request for a book by any person.
So I added a unique index like so -

TradeRequestSchema.index({_requester: 1, _requestedBook: 1, status: 1}, {unique: true});

Problem is this prevents some data to be entered in the database which should be allowed.

For example it prevents my database to have following documents which is fine for my use case -

{_id: 1, _requester: 12345, _requestedBook: 9871212, status: "opened"}
{_id: 2, _requester: 12345, _requestedBook: 9871212, status: "opened"}

But it also prevents the following which is wrong for my use case.

For example if my database already has following documents -

{_id: 3, _requester: 12345, _requestedBook: 9871212, status: "closed"}
{_id: 4, _requester: 12345, _requestedBook: 9871212, status: "opened"}

I cannot change request with id 4 to closed now which is wrong.

Basically what I want is to have a single opened request for a book but multiple closed requests.

How do I achieve this?



via Yasser Hussain

No comments:

Post a Comment