Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - Ensure unique field value in loopback model

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 loopback to through an error, on duplicate key insertion.

{
  "name": "Post",
  "plural": "Post",
  "base": "PersistedModel",
  "properties": {
    "genericId": {
      "type": "string",
      "required":True 
    },
    "moderatedAt": {
      "type": "date"
    }
  },
  "validations": [],
  "acls": [],
  "methods": []
}

I have tried searching there documentation, and other examples but no success. One solution which I can think of is, to create a remoteHook for the create function, and validate this field before inserting, but looking for some other way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    },
 ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...