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

守給你的承諾、 提交于 2019-12-11 18:26:20

问题


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


回答1:


@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.



来源:https://stackoverflow.com/questions/55993621/how-to-make-a-model-in-loopback-4-to-have-unique-values-in-its-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!