【发布时间】:2021-01-25 13:37:11
【问题描述】:
我是这个东西的新手,我在问如何从 MySQL 表中执行这个嵌套数组的示例,以输出像 node js express API 的 javascript 中的聊天示例一样,我使用的是 vue-cli。
查看chats Mysql 表:
Mysql chat table
这就是我想要达到的目标:
chats: {
SENDER ID -> 1: {
isPinned: true,
msg: [
{ // this is me (sender)
textContent: 'How can we help? We\'re here for you!',
time: 'Mon Dec 10 2018 07:45:00 GMT+0000 (GMT)',
isSent: true,
isSeen: true
},
{ // this is the receiver
textContent: 'Hey John, I am looking for the best admin template. Could you please help me to find it out?',
time: 'Mon Dec 10 2018 07:45:23 GMT+0000 (GMT)',
isSent: false,
isSeen: true
}
]
},
2: {
isPinned: false,
msg: [
{
textContent: 'Hi',
time: 'Mon Dec 10 2018 07:45:00 GMT+0000 (GMT)',
isSent: true,
isSeen: true
},
{
textContent: 'Hello. How can I help You?',
time: 'Mon Dec 11 2018 07:45:15 GMT+0000 (GMT)',
isSent: false,
isSeen: true
}
]
}
}
这是我到目前为止所做的: mysql查询:
getChats: callBack => {
pool.query(
'SELECT * FROM chat WHERE reciever_userid=1 AND sender_userid=5 OR sender_userid=1 AND reciever_userid=5 ORDER BY time',
[],
(error, chats) => {
if (error) {
callBack(error)
}
return callBack(null, chats)
}
)
}
API 调用:
getChats((err, chatz) => {
if (err) {
console.log(err)
return
}
const chats = chatz.map(el => {
el.msg = {
textContent : el.textContent || null,
time : el.time || null,
isSent : el.isSent || null,
isSeen : el.isSeen || null
}
delete el['status']
delete el['sender_userid']
delete el['reciever_userid']
delete el['textContent']
delete el['time']
delete el['isSent']
delete el['isSeen']
delete el['id']
return el
}).flat()
return res.json({
chats
})
})
邮递员的结果不是我在上面的例子中寻找的。p>
{
"chats": [
{
"isPinned": "true",
"msg": {
"textContent": "heyyy",
"time": "2020-10-07T15:04:40.000Z",
"isSent": "true",
"isSeen": "true"
}
},
{
"isPinned": "true",
"msg": {
"textContent": "yesss",
"time": "2020-10-07T15:04:40.000Z",
"isSent": "true",
"isSeen": "true"
}
}
]
}
【问题讨论】:
-
所以问题是您将聊天作为数组而不是带有索引的对象?或者那个味精是一个对象而不是一个数组?还是两者兼而有之?
-
我不知道像示例中那样输出热输出 1: { 在前面
-
好的,看看我的回答
标签: javascript mysql node.js arrays nested