JavaScript:
exports.userWithoutProject = async (req, res, next) => {
try {
let benchUser = [];
const project = await Project.find({})
const users = await User.find({}, {
email: 1,
_id: 0
})
for (let i = 0; i < users.length; i++) {
for (let j = 0; j < project.length; j++) {
for (let k = 0; k < project[j].seats.length; k++) {
if (users[i].email !== project[j].seats[k].employee && project[j].seats[k].employee === undefined) {
benchUser.push(users[i].email)
}
}
}
}
const uniq = [...new Set(benchUser)];
return res.json({
users: uniq
})
} catch (error) {
next(error)
}
}
用户:
[{
email: 'user1@email.com',
}, {
email: 'user2@email.com',
}, {
email: 'user3@email.com'
}]
项目(对象数组):
{ _id: 5cc2dd2eb3eea7004c9a7240,
name: 'Project One',
description:
'Lorem Ipsum',
start: '2018-06-01T09:45:00.000Z',
end: '2019-12-31T09:45:00.000Z',
seats:
[
{
skills: [Array],
_id: 5cc2e3cab3eea7004c9a724a,
start: '2018-06-01T09:45:00.000Z',
end: '2019-12-31T09:45:00.000Z',
potentialExtension: '2020-06-31T09:45:00.000Z',
role: 'Dev',
approved: true,
workload: 10,
employee: 'user1@email.com'
},
{
skills: [Array],
_id: 5cc2e3cab3eea7004c9a7241,
start: '2018-06-01T09:45:00.000Z',
end: '2019-12-31T09:45:00.000Z',
potentialExtension: '2020-06-31T09:45:00.000Z',
role: 'PM',
approved: true,
workload: 20,
employee: 'user3@email.com'
}
]
}
我的目标:
我想让所有没有项目席位的用户退回。
我有多个项目,每个项目都有一个seat
,其中用户电子邮件写在employee
字段中。因此,我必须浏览所有项目,并遍历每个项目席位,以检查我的用户是否匹配。
我从上面的方法返回user2@email.com
正确,但返回user1@email.com
却不正确。
答案 0 :(得分:1)
您可以使用Array.prototype.filter和Array.prototype.includes
来满足您的要求。
let users = [{
email: 'user1@email.com',
}, {
email: 'user2@email.com',
}, {
email: 'user3@email.com'
}];
let projects = [{ _id: '5cc2dd2eb3eea7004c9a7240',
name: 'Project One',
description:
'Lorem Ipsum',
start: '2018-06-01T09:45:00.000Z',
end: '2019-12-31T09:45:00.000Z',
seats:
[
{
skills: [Array],
_id: '5cc2e3cab3eea7004c9a724a',
start: '2018-06-01T09:45:00.000Z',
end: '2019-12-31T09:45:00.000Z',
potentialExtension: '2020-06-31T09:45:00.000Z',
role: 'Dev',
approved: true,
workload: 10,
employee: 'user1@email.com'
},
{
skills: [Array],
_id: '5cc2e3cab3eea7004c9a7241',
start: '2018-06-01T09:45:00.000Z',
end: '2019-12-31T09:45:00.000Z',
potentialExtension: '2020-06-31T09:45:00.000Z',
role: 'PM',
approved: true,
workload: 20,
employee: 'user3@email.com'
}
]
}];
let projectUsers = new Set();
projects.forEach(({seats}) => {
seats.forEach(({employee}) => projectUsers.add(employee));
});
let out = users.filter(({email}) => !Array.from(projectUsers).includes(email));
console.log(out)