Sequelize将MySql存储过程数据作为数组获取?

时间:2018-02-16 02:05:57

标签: mysql json stored-procedures sequelize.js

如果我在sequelize中调用存储过程,就像这样:

var query = "CALL GetSatellites();"
sequelize.query(query, { type: sequelize.QueryTypes.SELECT})
         .spread(responseWithResult(res))
         .catch(handleError(res));

和.json()转换它,我得到:

{
  "0": {
    "timestamp": "2018-02-13T00:00:00.000Z",
    "severity": "critical",
    "device": "battery",
    "identifier": "P2",
    "name": "P2 Battery Recover",
    "detail": ""
  },
  "1": {
    "timestamp": "2018-02-13T00:00:00.000Z",
    "severity": "critical",
    "device": "battery",
    "identifier": "P3",
    "name": "P3 Battery Recover",
    "detail": ""
  }
}

但我真的很喜欢它来做一个非常相似的SELECT查询时得到的更常见的输出:

var query = "SELECT * FROM Satellites;"
sequelize.query(query, { type: sequelize.QueryTypes.SELECT})
         .then(responseWithResult(res))
         .catch(handleError(res));

当.json()'d,我得到:

[
  {
    "_id": 4,
    "SatelliteId": 1,
    "createdAt": "2018-02-12T00:00:00.000Z",
    "updatedAt": "2018-02-12T00:00:00.000Z",
    "satelliteUTCTime": "2018-02-12T00:00:00.000Z",
    "identifier": "P1",
    "name": "P1 Battery Recover",
    "severity": "critical",
    "device": "battery",
    "detail": "Kablooee!"
  },
  {
    "_id": 5,
    "SatelliteId": 1,
    "createdAt": "2018-02-13T00:00:00.000Z",
    "updatedAt": "2018-02-13T00:00:00.000Z",
    "satelliteUTCTime": "2018-02-13T00:00:00.000Z",
    "identifier": "P2",
    "name": "P2 Battery Recover",
    "severity": "critical",
    "device": "battery",
    "detail": ""
  }
]

我已经使用spread()来获取存储过程返回的元数据了,但是有一些设置或调用sequelize我可以用来从存储过程调用中获取一个干净的对象数组,就像我一样直接SELECT?

2 个答案:

答案 0 :(得分:0)

您应该使用类型:sequelize.QueryTypes.RAW.then而不是.spread。 这对我有用。可能是因为没有为过程调用设置Model。

答案 1 :(得分:0)

您将必须在SP中设置一个OUT参数。

这是演示代码:

sequelize.query('SET @outputData = null; CALL stored_procedure (:someInputData, @outputData); SELECT @outputData;',
    {
      replacements: {
        someInputData: 'Send Your Data Here',
      },
      type: sequelize.QueryTypes.RAW,
    })
    .spread(response => console.log(response, 'response'))
    .error((error) => {
      console.log(error, 'errored');
    });

注意:创建实例时,在序列化配置中添加“ multipleStatements:true”,如下所示:

const sequelize = new Sequelize(config.database.dbName, config.database.username, config.database.password,
  {
    host: config.database.host,
    dialect: config.database.dialect,
    logging: false,
    dialectOptions: {
      multipleStatements: true,
    },
  });