Ensure unique field value in loopback model

前端 未结 3 528
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 17:29

How to ensure uniqueness of a particular field in loopback model. Like below is the model Post, I have a field genericId in it, I want it to be unique in the database, and l

相关标签:
3条回答
  • 2020-12-28 17:40

    Set validation rule in your common/models/post.js

    Post.validatesUniquenessOf('genericId');
    
    0 讨论(0)
  • 2020-12-28 17:54

    Not sure if it is the better way to achieve uniqueness, but you can find here the docs about indexing your model.

    Just add a unique index on the field you want, and voila !

    For your model, that would be :

    {
      ...
        "genericId": {
          "type": "string",
          "required": True,
          "index": {"unique": true} 
        },
     ...
    }
    

    However, if the genericId field is the actual Id of the model, I suggest you declare it as such, so you can use findById method, and also avoid creation of a duplicate id field, which will happen if you don't declare any in your model.

    {
      ...
        "genericId": {
          "type": "string", 
          "id": true,       // Ensure uniqueness and avoid another model id field
          "generated": true // Add this if you want Loopback to manage id content for you
        },
     ...
    }
    
    0 讨论(0)
  • 2020-12-28 18:02

    The Lookback v4 solution looks like this:

    @model()
    export class Client extends Entity {
    
      @property({
        type: 'string',
        required: true,
        index: {
          unique: true,
        },
      })
      name: string;
    
    }
    

    Then you must update your schema:

    npm run migrate
    

    or recreate it:

    npm run migrate -- --rebuild
    
    0 讨论(0)
提交回复
热议问题