如何创建随机字符串作为主键的Loopback模型?

时间:2017-11-09 20:42:08

标签: loopbackjs strongloop loopback

TL; DR

如何让Accounts.create({ provider: "facebook" })自动创建id主键?

描述

给定持久的Loopback模型定义

{
  "name": "Account",
  "plural": "accounts",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "id": true,
      "type": "string",
      "required": true
    },
    "provider": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "acls": [],
  "methods": {}
}

如何在Account.js添加远程方法以自动创建随机字符串作为主键?

3 个答案:

答案 0 :(得分:1)

尝试将此作为属性添加到模型的json文件中:

"id": {
  "type": "string",
  "id": true,
  "defaultFn": "uuid"
},

这应该自动生成随机主键为uuid。

答案 1 :(得分:0)

您可以在before save操作挂钩中创建新实例时设置它:

Model.observe('before save', (ctx, next) => {

    // If not acting on an instance or property already set, continue.
    if (!ctx.instance || ctx.instance.id) {
        return next();
    }

    ctx.instance.id = uuid();

    next();

});

答案 2 :(得分:0)

设置

"idInjection": true,

并添加

"id": {
  "type": "string",
  "id": true,
  "defaultFn": "uuid"
},