2015-01-02 43 views
1

我想創建一個以uuid字段爲主鍵的「客戶」模型。這似乎很簡單,但它不是因爲Waterline不包含任何本地驗證器。Waterline UUID類型和驗證

如何編輯此代碼,以便我可以將uuid作爲此模型的唯一主鍵?

module.exports = { 
    identity: 'customer', 
    connection: 'mysql', 
    attributes: { 
    // Properties 
    uuid: { 
     type: 'string', 
     primaryKey: true, 
     unique: true, 
     index: true, 
     uuidv4: true, 
    }, 
    firstName: { 
     type: 'string', 
    }, 
    // … 
    } 
}; 

非常感謝。

回答

3

我正在想方設法做同樣的事情,並找到了兩種方法。

  1. 使用包,比如node-uuid

    var uuid = require('node-uuid'); 
    

    ,然後在模型

    autoPK: false, 
    
    attributes: { 
        uuid: { 
         type: 'string', 
         primaryKey: true, 
         defaultsTo: function(){ return uuid.v4(); }, 
         unique: true, 
         index: true, 
         uuidv4: true 
        }, 
        // ... 
    } 
    

    設置autoPK爲false是爲了防止從水線自動生成的ID。

    參考:Feature Request: GUIDs as Primary Keys

  2. 通過使用包像node-uuidbeforeCreate

    var uuid = require('node-uuid'); 
    

    ,然後在模型

    autoPK: false, 
    
    attributes: { 
        uuid: { 
         type: 'string', 
         primaryKey: true, 
         unique: true, 
         index: true, 
         uuidv4: true 
        }, 
        // ... 
    }, 
    
    beforeValidate: function(values, next) { 
        values.uuid = uuid.v4(); 
        next(); 
    } 
    

    參考:

我喜歡的第一個原因很簡單,但它依賴。

希望這會有所幫助。

+0

[node-uuid](https://www.npmjs.com/package/node-uuid)在帖子中提到。 – Mak

+0

我嘗試了兩種基於node-uuid的解決方案。我有一個函數用100個測試記錄填充我的數據庫。只有第一個插入是因爲下一個生成的uuids發生了碰撞。我不理解爲什麼。 – mastergap

+0

@mastergap可能是因爲您在模型中生成了uuid作爲默認值,而不是使其成爲由水線執行的用於生成默認值的函數。 –