Search code examples
mongodbtypescriptloopbackjs

How to make a model in loopback 4 to have unique values in its schema?


I am trying to find a way to have the same funtionality that happens when I put unique:true in express schema. How do I accomplish this in loopback 4. I tried putting unique true in the property decorator but it did not work.

@property({
    type: 'string',
    id: true,
    required: false,
    unique: true,
  })
  id: string;

This doesnt work


Solution

  • @property decorator in LB4 borrows the same properties as in LB3. Assuming that I have understood your requirements, you can make use of the index property to enforce the uniqueness of a field across the collection. For a field like 'id', the property decorator would take the following arguments:

    @property({
        type: 'string',
        id: true,
        required: false,
        index: {
            unique: true
        }
      })
      id: string;
    

    Moreover, if you are using the 'id' generated by MongoDB, you do not need to enforce uniqueness explicitly but the above should work for other fields like email, username etc.