3

我们正在使用 Sails.js 作为后端框架将项目从 PHP 迁移到 Node.js。我们不能修改我们的数据库,并且必须为这个项目使用现有的数据库。

如果我migrate: "alter"为新创建的模型保留 ,默认情况下,Sails 会将id字段保留为整数。

但是,对于我们现有的数据库,id字段大多是bigint. 所以我定义migrate: "safe"并继续创建模型。

现在我面临的问题是,当蓝图路由返回结果时,应该作为数字返回的 id 列值改为作为字符串返回。这是一个例子:

[
  {
    "starttime": "07:00:00",
    "endtime": "14:00:00",
    "id": "1"
  },
  {
    "starttime": "14:00:00",
    "endtime": "22:00:00",
    "id": "2"
  },
  {
    "starttime": "22:00:00",
    "endtime": "07:00:00",
    "id": "3"
  }
]

我该如何解决这个问题?

这是我的模型:

module.exports = {
  tableName: "timeslots",
  autoCreatedAt: false,
  autoUpdatedAt: false,
  attributes: {
    starttime: { type: "string", required: true },
    endtime: { type: "string", required: true }
  }
};

这是postgresql表定义

                                              Table "public.timeslots"
  Column   |  Type  |                       Modifiers                        | Storage  | Stats target | Description 
-----------+--------+--------------------------------------------------------+----------+--------------+-------------
 id        | bigint | not null default nextval('timeslots_id_seq'::regclass) | plain    |              | 
 starttime | text   | not null                                               | extended |              | 
 endtime   | text   | not null                                               | extended |              | 
Indexes:
    "idx_43504_primary" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "doctortimeslot" CONSTRAINT "doctortimeslot_ibfk_2" FOREIGN KEY (timeslot_id) REFERENCES timeslots(id) ON UPDATE CASCADE ON DELETE CASCADE
4

2 回答 2

4

Waterline 对于它没有内置的数据类型变得很奇怪。我认为当它不确定该怎么做时它默认为字符串。这并不重要,因为 JS 会自动将这些值强制转换为前端的数字。

但是,如果您需要它是一个数字,最简单的解决方案可能是覆盖模型中的 toJSON 方法并将其强制为整数。

module.exports = {
  tableName: "timeslots",
  autoCreatedAt: false,
  autoUpdatedAt: false,
  attributes: {
    starttime: { type: "string", required: true },
    endtime: { type: "string", required: true },

    toJSON: function(){
      var obj = this.toObject();
      obj.id = parseInt(obj.id);
      return obj;
    }

  }
};
于 2015-10-03T08:29:55.530 回答
0

作为替代方案,您可以使用https://github.com/mirek/node-pg-safe-numbers通过将不安全处理委托给您(当数字不符合 2^53 javascript 限制时)来准确处理此问题 - 其中您可以返回解析值、字符串、null、抛出错误或执行其他操作。

在许多情况下,您可以使用库提供的自动解析,并且在不安全的处理程序中只返回原始字符串值。然后在使用大于 2^53 的数字(即随机大数字)的代码中总是转换为字符串,你会没事的。

于 2015-10-29T22:55:35.367 回答