Sequelize原始查询不会返回Postgres DB

时间:2018-04-12 12:47:17

标签: node.js sequelize.js sequelize-cli

我有一个sequelize原始查询来从数据库中选择一些值。但是当在postgres中运行查询时,即由sequelize生成给出2行并且在sequelize输出中,它只返回1行,返回的值是两行的混合以下是我的代码。

const Sequelize = require('sequelize');
let sequelize;
sequelize = new Sequelize('db_oauth2','postgres', 'postgres',{ host: 'localhost',dialect: 'postgres'});
const invoices = await sequelize.query("SELECT invoice_amount,  bill_period_from,to_char(bill_period_from,'Month') as month, bill_period_to FROM invoices  WHERE invoices.user_id="+user_id+" and date_part('year', bill_period_from) = date_part('year', current_date) order by bill_period_from", { type: db.sequelize.QueryTypes.RAW});
console.log(invoices);

从控制台输出输出

Executing (default): SELECT invoice_amount,  bill_period_from,to_char(bill_period_from,'Month') as month, bill_period_to FROM invoices  WHERE invoices.user_id=112 and date_part('year', bill_period_from) = date_part('year', current_date) order by bill_period_from

[ [ anonymous {
      invoice_amount: '120.000',
      bill_period_from: 2018-01-31T18:30:00.000Z,
      month: 'January  ',
      bill_period_to: 2018-02-27T18:30:00.000Z } ],
  Result {
    command: 'SELECT',
    rowCount: 1,
    oid: null,
    rows: [ [Object] ],
    fields: [ [Object], [Object], [Object], [Object] ],
    _parsers: 
     [ [Function],
       [Function: parseDate],
       [Function: noParse],
       [Function: parseDate] ],
    RowCtor: [Function: anonymous],
    rowAsArray: false,
    _getTypeParser: [Function: bound ] } ]

我执行了从postgres客户端控制台复制的相同查询,得到的结果如下

(invoice_amount;bill_period_from;month,bill_period_to)
300.000;"2018-01-01 00:00:00+05:30";"January  ";"2018-01-31 00:00:00+05:30"
120.000;"2018-02-01 00:00:00+05:30";"February ";"2018-02-28 00:00:00+05:30"

所以在sequelize中,它只检索一行,即postgres输出中的第二行,列月的值是postgres输出中的第一行。如果发生这种情况,则sequelize不是稳定的ORM。 Sequelize版本4.26 Postgres 9.5

1 个答案:

答案 0 :(得分:0)

默认情况下,sequelize.query(sql,options)的options.type等于raw,并返回带有Result对象的完整响应。

通过将options.type指定为sequelize.QueryTypes.SELECT,您可以获得仅数据响应。

请参阅官方docs