Ensure unique field value in loopback model
Asked Answered
E

3

21

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.

Extol answered 19/9, 2014 at 6:48 Comment(2)
you can also enforce uniqueness on your database directlyBruyn
Yes, Strongloop's LoopbackJS documentation is impossibly miserable.Reeher
M
28

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

Post.validatesUniquenessOf('genericId');
Mix answered 26/11, 2014 at 12:23 Comment(4)
Thanks for the solution, but have already got it, sorry forgot to update it here.Extol
Correct validation docs docs.strongloop.com/display/APIC/Validating+model+dataApologetic
Only supported connectors: In Memory, Oracle or MongoDBApologetic
What if I want to keep combination of fields to be unique?Spruce
D
30

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
    },
 ...
}
Distinctive answered 19/9, 2014 at 14:20 Comment(2)
Could you expend on "...declare it as such"? Thanks.Foveola
Note: this is an old post, not sure if its still valid. In the above message, the code expands on the explanation : you declare a field as a model ID by setting the id prop (to true) in the field json definition.Distinctive
M
28

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

Post.validatesUniquenessOf('genericId');
Mix answered 26/11, 2014 at 12:23 Comment(4)
Thanks for the solution, but have already got it, sorry forgot to update it here.Extol
Correct validation docs docs.strongloop.com/display/APIC/Validating+model+dataApologetic
Only supported connectors: In Memory, Oracle or MongoDBApologetic
What if I want to keep combination of fields to be unique?Spruce
H
10

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
Hooray answered 10/2, 2019 at 4:56 Comment(4)
Did you update your schema? npm run migrate or npm run migrate -- --rebuild?Hooray
Not every connector might support this. I checked it for PostgreSQL. MySQL is supported, too, I guess.Hooray
Thank you Mathias, this is what I've been looking for. Tested in PostgreSQL. Btw, it doesn't send a good error message for the response. The error response now would only be 500. Does any of you have reference for editing that? Thank you!Kovach
This answer is more elegant and also correct one for Mongo Driver, in my opinionAuberon

© 2022 - 2024 — McMap. All rights reserved.