我們正在使用Sails.js作爲後端框架將項目從PHP遷移到Node.js。我們不能修改我們的數據庫,並且不得不爲現有的數據庫使用這個項目。sails.js -postgresql爲bigint字段返回字符串值而不是整數
如果我爲新創建的模型保留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
完美!重寫toJSON方法對我來說是一個理想的解決方案,因爲API將被本機android和iOS應用程序使用。謝謝! –
無論如何,是否有可能爲所有模型重寫此方法,而無需在每個模型中明確指定? –
找到它了。在model.js文件中指定'attributes:{ toJSON:function(){var _j = this.toObject(); obj.id = parseInt(obj.id); return obj; } }' –