在Sails.js中从PostgreSQL获取BYTEA

我在处理Sails.js中的PostgreSQL BYTEAtypes时遇到了问题。

表定义(是的,创build二进制PK是奇怪的,但some_data总是很小):

CREATE TABLE data_blobs ( some_data BYTEA PRIMARY KEY, my_date_time TIMESTAMP WITH TIME ZONE NOT NULL); 

模型configuration如下所示:

 module.exports = { tableName: 'data_blobs', autoCreatedAt: false, autoUpdatedAt: false, autoPK: false, attributes: { some_data: { type: 'binary', primaryKey: true }, my_date_time: 'datetime', }; 

当我使用node-postgres(pg)从node.js查询表时,结果包含了使用some_data的节点缓冲区,这非常容易使用。

但是,当我从Sails.js查询表使用这样的代码:

 DataBlobs.find().then(function(result){ console.log('Result: '); console.log(result); }); 

结果如下所示:

 { some_data: { '0': 1, '1': 79, '2': 95, ... '19': 216, length: 20, parent: { '0': 47, ... '8191': 0 } }, my_date_time: '2015-08-24T10:43:11.959Z' } 

在我看来,Waterline将节点缓冲区转换为奇怪的东西并且毫无用处(没有额外的转换)。 我找不到任何有关数据转换的文档,不在Waterline文档中,也不在sails-postgresql文档中。

我看到了两个select来处理这种情况:

  1. 不知何故,以防止水线转换缓冲区,并做我自己的转换。
  2. 获取水线输出并将其转换为控制器。

第二个选项似乎不太有效,因为原始数据附加了大的“父”,并且会有两个转换Buffer-> Waterline-> MyFormat而不是简单的Buffer-> MyFormat。

我find的第一个解决scheme是基于将水线模型函数replace为JSON的想法( https://github.com/balderdashy/waterline#model )。

我写了一个转换函数:

 function internalWaterlineBinaryToBase64(waterlineBinaryRepresentation) { var temporaryArray = []; for(var i = 0, arrLength = waterlineBinaryRepresentation.length; i < arrLength; i++) { temporaryArray.push(waterlineBinaryRepresentation[i.toString()]); } var temporaryBuffer = new Buffer(temporaryArray); return temporaryBuffer.toString('base64'); } 

并调整我的模型:

 module.exports = { tableName: 'data_blobs', autoCreatedAt: false, autoUpdatedAt: false, autoPK: false, attributes: { some_data: { type: 'binary', primaryKey: true }, my_date_time: 'datetime', toJSON: function() { var obj = this.toObject(); if(obj.some_data) { obj.some_data = internalWaterlineBinaryToBase64(obj.some_data); } return obj; } }; 

它工作正常,但在我看来,应该有一个更便宜的方法(水线将原始的缓冲区转换为对象,然后我将其转换为数组,然后到缓冲区,然后再转换为string)。