gpt4 book ai didi

javascript - MongoDB 仅返回其他文档中的用户与字段不匹配的文档

转载 作者:行者123 更新时间:2023-12-02 23:44:23 25 4
gpt4 key购买 nike

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'
}
]
}

我的目标:

我希望返回所有没有项目席位的用户。

我有多个项目,每个项目都有一个席位,用户电子邮件地址写入员工字段中。因此,我必须遍历所有项目,并循环遍历每个项目席位以检查我的用户是否匹配。

我的方法从上面返回我 user2@email.com 这是正确的,但也 user1@email.com 这是不正确的。

最佳答案

您可以使用以下方式实现您的要求:Array.prototype.filterArray.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)

关于javascript - MongoDB 仅返回其他文档中的用户与字段不匹配的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55916185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com