我在PostgreSQL中有以下查询:
select bookings."memberId" from bookings
join "memberConnections" mbc on bookings."memberId" = mbc."memberId"
join shifts shf on shf.id = bookings."shiftId"
where bookings.state = 'WAITING_LIST' and (mbc.state = 'LOCKED' or mbc.state = 'REMOVED')
and shf."startTime" > CURRENT_TIMESTAMP;
我正在将其导入文件中,然后通过名为的库处理数据 Knex.js
当我运行它并控制台记录查询时,我得到以下结构:
USER_STATE: Result {
command: 'SELECT',
rowCount: 32,
oid: NaN,
rows:
[ anonymous { memberId: 1800 },
anonymous { memberId: 15476 },
anonymous { memberId: 15476 },
anonymous { memberId: 15476 },
anonymous { memberId: 12553 },
anonymous { memberId: 12553 },
anonymous { memberId: 19668 },
anonymous { memberId: 19668 },
anonymous { memberId: 21004 },
anonymous { memberId: 21004 },
anonymous { memberId: 21004 },
anonymous { memberId: 21004 },
anonymous { memberId: 16105 },
anonymous { memberId: 14927 },
anonymous { memberId: 15476 },
anonymous { memberId: 12553 },
anonymous { memberId: 12553 },
anonymous { memberId: 12553 },
anonymous { memberId: 12553 },
anonymous { memberId: 17923 },
anonymous { memberId: 17273 },
anonymous { memberId: 12553 },
anonymous { memberId: 12553 },
anonymous { memberId: 19429 },
anonymous { memberId: 17312 },
anonymous { memberId: 17273 },
anonymous { memberId: 15476 },
anonymous { memberId: 15476 },
anonymous { memberId: 15476 },
anonymous { memberId: 15476 },
anonymous { memberId: 15476 },
anonymous { memberId: 19634 } ],
fields:
[ Field {
name: 'memberId',
tableID: 22531,
columnID: 3,
dataTypeID: 23,
dataTypeSize: 4,
dataTypeModifier: -1,
format: 'text' } ],
_parsers: [ [Function: parseInteger] ],
RowCtor: [Function: anonymous],
rowAsArray: false,
_getTypeParser: [Function: bound ] }
这几乎是我所需要的,但是,我只需要memberId数据,有什么方法可以通过它映射以仅获取memberId属性?
我已经尝试过了,但是似乎不起作用:
const users = userState.map(users => ({
memberId: memberId;
}))
答案 0 :(得分:1)
您首先需要将该结构转换为 valid JSON 。然后,您可以根据需要在
userState.rows
上进行处理。
Here 是将 knex.js 响应转换为JSON的参考。
这是使用有效JSON的有效示例-
var userState = {
rows:
[{ memberId: 1800 },
{ memberId: 15476 },
{ memberId: 15476 },
{ memberId: 12553 },
{ memberId: 12553 },
{ memberId: 19668 },
{ memberId: 19668 },
{ memberId: 21004 },
{ memberId: 21004 },
{ memberId: 19634 }],
fields:
[{
name: 'memberId',
tableID: 22531,
columnID: 3,
dataTypeID: 23,
dataTypeSize: 4,
dataTypeModifier: -1,
format: 'text'
}]
};
var data = userState.rows.map((users, index) =>
users.memberId
);
console.log(data);
答案 1 :(得分:0)
尝试一下
const userState = {
rows: [
{ memberId: 1 },
{ memberId: 2 }
]
}
const users = userState.rows.map(users =>
users.memberId
)
console.log(users)
// [ 1, 2 ]
答案 2 :(得分:0)
我认为这会对您有所帮助:https://knexjs.org/#Interfaces-map
我认为是错误的
.map(users => ({
memberId: memberId;
}))
应该是:
.map(function(row) {
return row.memberId;
})
您可以尝试我的解决方案,它可能会起作用,因为我没有将Knex.js与Node.JS一起用于SQL,我通常Sequelize