Search code examples
node.jsexpresssails.jswaterline

Unique property fails in Sails.js


The following code represents an Account Model in Sails.js v0.9.4 .

 module.exports = {

      attributes: {
        email: {
          type: 'email',
          unique: true,
          required: true
        },
        password:{
          type: 'string',
          minLength: 6,
          maxLength: 15,
          required:true
        }
      }

    };

When I send two POSTS and a PUT request via Postman to localhost:8080/account, the unique property of the email fails. Specifically, I send the following HTTP requests from Postman:

POST http://localhost:8080/[email protected]&password=123456  
POST http://localhost:8080/[email protected]&password=123456    
PUT  http://localhost:8080/account?id=1&[email protected]  
GET  http://localhost:8080/account

The last GET request shows me:

[
  {
    "email": "[email protected]",
    "password": "123456",
    "createdAt": "2013-09-30T18:33:00.415Z",
    "updatedAt": "2013-09-30T18:34:35.349Z",
    "id": 1
  },
  {
    "email": "[email protected]",
    "password": "123456",
    "createdAt": "2013-09-30T18:33:44.402Z",
    "updatedAt": "2013-09-30T18:33:44.402Z",
    "id": 2
  }
]

Should this happen?
*For those who don't know, Waterline generates by default an id which automatically increments in every insertion.


Solution

  • This is because your schema is not updated in your disk database (".tmp/disk.db").

    You need to shutdown sails, drop your DB and restart sails. The DB will be reconstruct with your good schema.

    Attention : the data will be drop too !

    If you want keep your data, you can just update the schema part of ".tmp/disk.db".

    What I have doing to keep data and rebuild schema by sails.js :

    1. copy ".tmp/disk.db"
    2. clean ".tmp/disk.db"
    3. shutdown sails.js
    4. start sails.js -> the database is empty and the schema is updated
    5. copy old "counters" part
    6. copy old "data" part

    You must have this in your schema (file ".tmp/disk.db" -> "schema" part) for the unique field :

      "xxx": {
        "type": "string",
        "unique": true
      },
    

    I hope this help you.