我有一个mongodb查询,然后使用for循环结果并将某些项目推入新数组。但是输出显示同一对象n次。
if语句很好,查询也可以,问题出在对closedTickets的推送中,我先打印要推送的对象,然后再推送它,但是我得到了奇怪的行为。 我尝试使用_id作为键的哈希图,如果该图没有键,则设置该对象,但没有成功,请帮帮我。
代码:
const ticketsQuery = await Action.aggregate([
{
$match: {
createdTime: { $gte: new Date(from), $lte: new Date(to) },
action: { $in: ['open', 'hold', 'pending', 'closed']}
}
}, {
$group: {
_id: '$task',
actions: {
$push: {
action: '$action',
date: '$createdTime'
}
}
}
}, {
$lookup: {
from: 'tasks',
localField: '_id',
foreignField: '_id',
as: 'task',
}
}, {
$match: {
'task.organization': orgID
}
}
]);
const ticket = {}
const closedTickets = [];
for (const ticketsQueryElement of ticketsQuery) {
ticket.closedAt = 0;
ticket.openAt = 0;
ticket.holdAt = 0;
ticket.pendingAt = 0;
ticket.task = ticketsQueryElement._id
for (const closedTicket of ticketsQueryElement.actions) {
if (closedTicket.action === 'open') {
if (ticket.openAt === 0) {
ticket.openAt = closedTicket.date;
} else if (ticket.openAt < closedTicket.date) {
ticket.openAt = closedTicket.date;
}
}
if (closedTicket.action === 'hold') {
if (ticket.holdAt === 0) {
ticket.holdAt = closedTicket.date;
} else if (ticket.holdAt < closedTicket.date) {
ticket.holdAt = closedTicket.date;
}
}
if (closedTicket.action === 'pending') {
if (ticket.pendingAt === 0) {
ticket.pendingAt = closedTicket.date;
} else if (ticket.pendingAt < closedTicket.date) {
ticket.pendingAt = closedTicket.date;
}
}
if (closedTicket.action === 'closed') {
if (ticket.closedAt === 0) {
ticket.closedAt = closedTicket.date;
} else if (ticket.closedAt < closedTicket.date) {
ticket.closedAt = closedTicket.date;
}
}
}
if ((ticket.openAt !== 0 || ticket.holdAt !== 0
|| ticket.pendingAt !== 0) && ticket.closedAt !== 0) {
// output 1
console.log(ticket)
closedTickets.push(ticket);
}
}
// output 2
console.log(closedTickets)
输出显示如下:
输出1:
{
closedAt: 2019-11-12T20:02:38.897Z,
openAt: 2019-11-11T18:04:10.296Z,
holdAt: 0,
pendingAt: 0,
task: 5dc6f9fad550ac3c68d8bcd3
}
{
closedAt: 2019-11-08T20:03:22.833Z,
openAt: 2019-11-07T17:08:10.769Z,
holdAt: 0,
pendingAt: 0,
task: 5dc37d03d550ac3c68d8aed6
}
{
closedAt: 2019-11-13T00:03:27.695Z,
openAt: 2019-11-11T20:08:10.305Z,
holdAt: 0,
pendingAt: 0,
task: 5dc9bdcb44386e3c697d61c9
}
输出2:
[
{
closedAt: 2019-11-08T17:03:54.984Z,
openAt: 2019-11-07T16:03:06.234Z,
holdAt: 0,
pendingAt: 0,
task: 5dc377638d25253b5cbaa5d4
},
{
closedAt: 2019-11-08T17:03:54.984Z,
openAt: 2019-11-07T16:03:06.234Z,
holdAt: 0,
pendingAt: 0,
task: 5dc377638d25253b5cbaa5d4
},
{
closedAt: 2019-11-08T17:03:54.984Z,
openAt: 2019-11-07T16:03:06.234Z,
holdAt: 0,
pendingAt: 0,
task: 5dc377638d25253b5cbaa5d4
}
]